
[英]C# compiler error: “cannot have instance field initializers in structs”
[英]Why C# compiler cannot bind instance Delegate during Field Initialization?
查看众所周知的CS0236 错误消息
错误 (CS0236):字段初始值设定项无法引用非静态字段、方法或属性,并且
这种限制的原因是初始化顺序:
您不能使用实例变量来初始化另一个实例变量。
this
不是实例变量,是吗? 我的问题是为什么即使对引用 class方法也有如此严格的要求? 据我了解,仅限制 class 方法的调用就足够了,例如:
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
类的东西似乎对初始化没有任何副作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.