Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 循环静态只读字段定义的奇怪行为_C#_Instantiation - Fatal编程技术网

C# 循环静态只读字段定义的奇怪行为

C# 循环静态只读字段定义的奇怪行为,c#,instantiation,C#,Instantiation,在Visual Studio 2017(调试构建)中运行以下代码时,我遇到了一点奇怪的行为: 这大概是我所期望的行为。但是,如果我取消对Program.Main(…)中第二行的注释,输出将更改为 Some other customer Mr. Nice Guy null null 我知道,通过将UnwantedCustomers转换为静态只读属性,可以很容易地解决这个问题 但我想知道所描述的行为是否与类和对象的初始化顺序有关,或者这种行为是否未定义?您有一个初始化顺序问题 static字段(和

在Visual Studio 2017(调试构建)中运行以下代码时,我遇到了一点奇怪的行为:

这大概是我所期望的行为。但是,如果我取消对Program.Main(…)中第二行的注释,输出将更改为

Some other customer
Mr. Nice Guy
null
null
我知道,通过将UnwantedCustomers转换为静态只读属性,可以很容易地解决这个问题


但我想知道所描述的行为是否与类和对象的初始化顺序有关,或者这种行为是否未定义?

您有一个初始化顺序问题

static
字段(和属性)是在静态构造函数运行之前初始化的(如果有静态构造函数,也可以运行)。这是在引用类的任何成员之前(静态或非静态)

注释掉lime后,当引用
Customer.UnwantedCustomers
时,它会触发
Customer
的静态构造,其前面是
DefaultCustomers
的静态构造

但是通过更容易地引用
DefaultCustomers
,它触发了
DefaultCustomers
的静态构造,这需要
Customer
的静态构造。这意味着
Customer
的静态属性在
defaultconstomer
的静态属性之前进行初始化。因此是无效的。在这种情况下,
Customer
的静态构造完成后,
DefaultCustomers
的静态构造将完成,因此,
DefaultCustomers.NiceCustomer
有一个值,但
Customer.UnwantedCustomers
包含空值

这是一种定义良好的行为,用一种即使没有帮助也可以预测的行为来覆盖这样的情况

您的问题是两种类型之间的循环引用。将
UnwantedCustomers
作为
DefaultCustomers
的一个字段可以避免这个问题

Some other customer
Mr. Evil Guy
Mr. Broke Guy
Some other customer
Mr. Nice Guy
null
null