gpt4 book ai didi

c# - 类静态成员的奇怪行为——这怎么可能?

转载 作者:太空狗 更新时间:2023-10-29 17:41:56 25 4
gpt4 key购买 nike

考虑以下类:

public class MyClass
{
public static string[] SomeAmazingConsts = { Const1 };
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
}

现在,检查用法:

class Program
{
static void Main(string[] args)
{
string[] s = MyClass.SomeAmazingConsts;
//s[0] == null
}
}

问题是 s[0] == null!这到底是怎么发生的?现在,将 MyClass 的静态变量重新排序如下:

public class MyClass
{
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
public static string[] SomeAmazingConsts = { Const1 };
}

一切开始正常工作。任何人都可以对此有所了解吗?

最佳答案

来自 10.4.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

因此初始化从上到下发生,在第一种情况下 Const1 尚未初始化,因此 null

关于c# - 类静态成员的奇怪行为——这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22927167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com