我有下面的代码类:为什么`this`在C#6.0自动属性初始化中不可用?
public class Foo
{
public Nested Bar { get; } = new Nested(this);
public class Nested
{
public Nested(Foo foo)
{
foo.DoSomething();
}
}
private void DoSomething()
{
}
}
不过,我得到这个编译错误:
Keyword 'this' is not available in the current context
我可以简单地通过不使用自动属性初始化程序修复它,并明确将其移动到构造函数代替:
public Nested Bar { get; }
public Foo()
{
this.Bar = new Nested(this);
}
为什么会这样?自动属性初始值设定项实际上是否转换为IL中的构造函数代码?
。您不能在字段初始值设定项中引用它,因为字段初始值设定项在构造函数之前运行,所以没有构建的对象尚未使用。 – Evk
@Evk是否这样,当构造函数运行时,对象也是“尚未构造”? –
一个有趣的问题Roland Pihlakas!该对象必须已经存在,正在准备访问的内存。否则,该物业不会在那里。但没有其他东西被初始化。人们可以在构造函数中执行初始化步骤的错误顺序,但对程序员来说更明显。 – Droidum