Why C# won't allow field initializer with non-static fields?

后端 未结 2 1308
一向
一向 2020-12-03 10:53

Why C# will allow this :

public class MyClass
{
  static int A=1;
  static int B=A+1;
}

But won\'t allow (\"A field initializer can

2条回答
  •  清歌不尽
    2020-12-03 11:11

    I'm more interested with the reason/logic for why it was restricted. just for curiosity.

    If you read the C# Language Spec, 10.11.3, it hints as to the rationale here. In discussing variable initializers:

    It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body.

    Since these are "inserted before the constructor", they are being executed prior to this being valid, so allowing you to refer to other members (effectively this) would be problematic.

    Note that this is consistent with how static fields work, as well. In both cases, you are allowed to access static data, but not instance data. The error message you receive ("A field initializer cannot reference the non-static field, method, or property") directly notes this.

提交回复
热议问题