gpt4 book ai didi

c# - 静态 ImmutableArray 未初始化

转载 作者:太空狗 更新时间:2023-10-29 22:57:16 24 4
gpt4 key购买 nike

我有一个带有静态成员的内部静态类 MyLists:

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

在另一个公共(public)测试类 Tests 中,我有一个 MyTest 函数来选择和比较列表。

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

但是,我收到以下错误:

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

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

最佳答案

根据 ImmutableArray 上的文档, 你应该使用 Create()方法而不是对这种类型的数组使用构造函数,如下所示:

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

关于为什么,我会点你这篇文章Please welcome ImmutableArray由 Immo Landwerth 撰写,他在其中描述:

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.

关于c# - 静态 ImmutableArray 未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633231/

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