查看众所周知的CS0236 error消息
错误(CS0236):字段初始化程序无法引用非静态 字段,方法或属性以及
reason对于这种限制是初始化顺序:
您不能使用实例变量来初始化另一个实例 变量。
但是this
不是实例变量,对吗?我的问题是,为什么甚至对 refrecing 类方法都有如此严格的要求?以我的理解,仅限制类方法的调用就足够了,例如:
bool _field;
bool GetField() => _field;
bool _field2 => GetField(); // clearly an error,invoking something that might not be initialized
// why compiler cannot safely bind a delegate? It does not have to access anything,just take an address
Func<bool> Func1 = GetField; // does not have to error,refencing but not invoking
这仅仅是设计决定还是有任何技术限制会阻止在字段初始化期间进行委托绑定?
编辑:我对技术方面很感兴趣,而不是修正错误。是什么阻止编译器绑定实例方法?绑定发生时this
的地址必须可用,并且类似funcPtr = instanceaddress+memberoffset
之类的东西似乎对初始化没有任何副作用。