本文介绍了静态变量顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对C#中的静态变量声明的顺序有疑问
I have aproblem with the order of static variable declaration in C#
当我运行此代码时:
static class Program {
private static int v1 = 15;
private static int v2 = v1;
static void Main(string[] args) {
Console.WriteLine("v2 = "+v2);
}
}
输出为:
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);
}
}
输出为:
v2 = 0
为什么会这样?
推荐答案
以与声明相同的顺序初始化静态字段.当您使用值 v1
初始化 v2
时, v1
尚未初始化,因此其值为0.
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.
这篇关于静态变量顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!