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

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

提交回复
热议问题