Class One Private myTwo As Two = New Two(Me) End Class Class Two Sub New(withOne As One) End Sub End Class
但是在C#中,你不能这样做:
class One { private Two myTwo = new Two(this); } class Two { public Two(One withOne) { } }
因为您收到错误“关键字”,所以在当前上下文中不可用.
我发现this question/answer报价the C# language specification部分7.6.7:
7.6.7 This access
A this-access is permitted only in the block of an instance constructor,an instance
method,or an instance accessor. … (specifics omitted) … Use of this in a primary-
expression in a context other than the ones listed above is a compile-time error. In
particular,it is not possible to refer to this in a static method,a static property
accessor,or in a variable-initializer of a field declaration.
此外,this question涵盖了它(尽管我的选择不够充分地回答),而在这里,OblivIoUs Sage对我的问题的回答解释了为什么 – 因为它是防止错误的功能.
为什么这个功能不在VB中?
Per Eric Lippert C#这样做,以便他们可以保证只读字段始终被初始化,然后才能被引用.
我没有看到它在任何地方明确表示,但如果我不得不猜测他们发现VB.NET中的缺陷,而C#仍在开发中;然后他们觉得这是一个足够大的问题,值得在C#中修复,但不是一个足够大的问题,可以使VB.NET发生变化(甚至是广泛的).