Static variable order [duplicate]

僤鯓⒐⒋嵵緔 提交于 2021-02-20 13:32:23

问题


I have aproblem with the order of static variable declaration in C#

When i run this code:

static class Program {
  private static int v1 = 15;
  private static int v2 = v1;

  static void Main(string[] args) {
   Console.WriteLine("v2 = "+v2);
  }
}

The output is:

v2=15

But when i change the static variable declaration order like this:

 static class Program {
      private static int v2 = v1;
      private static int v1 = 15;


      static void Main(string[] args) {
       Console.WriteLine("v2 = "+v2);
      }
    }

The Output is:

v2 = 0

Why this happend?


回答1:


The static fields are initialized in the same order as the declarations. When you initialize v2 with the value of v1, v1 is not initialized yet, so its value is 0.




回答2:


Static variables are initialized in their order of declaration, so when you are assigning v2 in your second example, v1 still has its default value 0.

I hope you know that doing things like this is a bad idea though.




回答3:


The way static variables get there value means that in the second example, v1 is not initialized and so takes on the default value of 0 when it is assigned to v2.




回答4:


The static fields initialized same order as follows their declarations.

In your second code, v1 isn't initialized. Since v1 is Int32, so it is a value type, and all value types default value is 0.

From C#4.0 in a Nutshell on page 74.

Static field initializers run in the order in which the fields are declared.

In your case;

private static int v2 = v1;
// v2 initialized 0 because of the default value of value types.
private static int v1 = 15;
// v1 initialized 15


来源:https://stackoverflow.com/questions/15388793/static-variable-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!