“字段初始值设定项无法引用非静态字段、方法或属性”的概念原因CS0236 错误
C# 不允许实例字段初始值设定项引用另一个字段。 例如,此代码无效:
class A
{
string s1 = "";
string s2 = s1;
}
因为“s2”引用“s1”。
但是为什么这是不允许的?
我的第一个想法是C#规范不保证任何初始化顺序,但根据规范,顺序是声明的顺序:
变量初始值设定项按照它们在类声明中出现的文本顺序执行。
那么,如果顺序是确定性的,这种代码可能存在哪些陷阱?
提前感谢您的帮助。
编辑:
根据Hps、0xA3和Peter的回答:
继承场景中的初始化顺序可能会非常混乱,
实现这样的功能需要编译器开发团队提供一些资源,但几乎没有什么好处,
出于逻辑原因不可能使用方法或属性(感谢Peter),因此为了保持一致性,字段也是如此。
C# does not allow an instance field initializer to reference another field.
For instance this code is not valid :
class A
{
string s1 = "";
string s2 = s1;
}
because "s2" references "s1".
But why this is not permitted ?
My first thought was that the C# specs do not guarantee any initialization order but according to the specs the order is the order of declaration :
The variable initializers are executed in the textual order in which they appear in the class declaration.
So if the order is deterministic what could be the pitfalls of this kind of code ?
Thanks in advance for your help.
EDIT :
According to the answers of Hps, 0xA3 and Peter :
order of initialization in inheritance scenario could be very confusing,
implementing such a feature would require some resources from the compiler development team for little benefit,
it's not possible to use method or properties for logical reasons (thanks Peter), so for consistency the same is true for fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定字段,但拒绝字段初始值设定项访问属性或方法似乎是合理的。例如:
I'm not sure about a field, but it seems rational to deny field initializers access to properties or methods. For example:
编译器可能可以检查字段的顺序,然后如果先前已声明了其他字段,则允许初始化。
除了重新排序或重新构造会破坏代码的陷阱之外,为什么编译器应该变得不必要的复杂。资源有限,编译器团队可能更喜欢开发优先级更高的功能。
The compiler probably could check the order of the fields and then allow initialization if the other field has been previously declared.
Besides the pitfall that re-ordering or re-structuring breaks your code, why should the compiler be unnecessarily complex. Resources are limited, and the compiler team probably prefers working on features with higher priority.