在 Visual Studio 2017(调试版本)中运行以下代码时,我遇到了一些奇怪的行为:
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Program
{
public static class DefaultCustomers
{
public static readonly Customer NiceCustomer = new Customer() { Name = "Mr. Nice Guy " };
public static readonly Customer EvilCustomer = new Customer() { Name = "Mr. Evil Guy " };
public static readonly Customer BrokeCustomer = new Customer() { Name = "Mr. Broke Guy" };
}
public class Customer
{
public static readonly IEnumerable<Customer> UnwantedCustomers = new[] { DefaultCustomers.EvilCustomer, DefaultCustomers.BrokeCustomer };
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
public static void Main(string[] args)
{
Console.WriteLine(new Customer() { Name = "Some other customer" });
//Console.WriteLine(DefaultCustomers.NiceCustomer);
foreach (var customer in Customer.UnwantedCustomers)
{
Console.WriteLine(customer != null ? customer.ToString() : "null");
}
Console.ReadLine();
}
}
}
控制台上的输出是
Some other customer
Mr. Evil Guy
Mr. Broke Guy
这大致是我预期的行为。但是,如果我取消注释 Program.Main(...) 中的第二行,输出将更改为
Some other customer
Mr. Nice Guy
null
null
我知道可以通过将 UnwantedCustomers 转换为静态只读属性来轻松解决此问题。
但我想知道所描述的行为是否遵循类和对象的初始化顺序,或者这种行为是否未定义?
慕桂英3389331
相关分类