静态 ImmutableArray 未初始化

static ImmutableArray is not initialized

我有一个内部静态 class MyLists 和一个静态成员

internal static ImmutableArray<string> MyList = new ImmutableArray<string> { "asd", "qwe" };

在另一个 public 测试 class 测试中,我有一个 MyTest 函数可以选择和比较列表。我得到一个

Additional information: The type initializer for 'TestMyLists' threw an exception. Object reference not set to an instance of an object.

[TestClass]
public class MyTests {
  [TestMethod]
  public void TestMyLists() {
    var list = MyLists.MyList.Select(s => s + ".foo");
  }
}

当我调试时,我看到静态 ImmutableArray 的值 = 未初始化。为什么?

MSDN 所述,对于此类数组,您应该使用 Create() 方法而不是使用构造函数:

internal static ImmutableArray<string> List = ImmutableArray.Create("asd", "qwe");

关于原因,我会向您指出 Immo Landwerth 的 article,他在其中描述:

The default value of ImmutableArray<T> has the underlying array initialized with a null reference. In this case it behaves the same way as an ImmutableArray<T> that has been initialized with an empty array, i.e. the Length property returns 0 and iterating over it simply doesn’t yield any values. In most cases this is the behavior you would expect. However, in some cases you may want to know that the underlying array hasn’t been initialized yet. For that reason ImmutableArray<T> provides the property IsDefault which returns true if the underlying array is a null reference. For example you can use that information to implement lazy initialization: