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

后端 未结 2 1298
一向
一向 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.

    0 讨论(0)
  • 2020-12-03 11:17

    "Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object." -static MSDN

    When A and B are declared static they belong to the type MyClass and all instances of MyClass will have the same value for A and B. The static constructor will run before the class is instantiated but after the program has started. At that point, A is already defined, and thus B can reference it.

    On the other hand, when A and B are not static, they only belong to the instance of MyClass. While compiling, the field B will attempt to be initialized based on a value from A which has not yet been initialized. There is no instance of MyClass while the compiler is running and therefore there is no value of A to reference.

    0 讨论(0)
提交回复
热议问题