ImmutableList 不包含采用 0 个参数的构造函数

我试图初始化一个像常规列表一样的不可变列表,但它告诉我它不需要 0 个参数。如果我传递 1 个参数、2 个参数等,它会抛出相同的错误。


public static readonly ImmutableList<object[]> AddressTestCases = new ImmutableList<object[]>

{

    new object[]{ "", false },

    new object[]{ "testestest", true },

};

我在这里做错了什么?有没有办法在不使用 .Add 的情况下做到这一点?


三国纷争
浏览 243回答 3
3回答

慕妹3242003

好的ImmutableList有一个你应该使用的 create 方法public ImmutableList<int> ImmutableListCreate(){&nbsp; &nbsp; return ImmutableList.Create<int>(1, 2, 3, 4, 5);}

冉冉说

您使用的语法不是调用您认为的构造函数。它正在调用空构造函数,然后在后台调用.Add您提供的对象数组。您将需要使用其中一种构建器方法:public static readonly ImmutableList<object[]> AddressTestCases =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new[] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new object[]{ "", false },&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new object[]{ "testestest", true }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).ToImmutableList();

一只萌萌小番薯

要创建 ImmutableList,您必须使用在 ImmutableList 静态类上定义的静态工厂方法 Create()。这意味着您将需要public&nbsp;static&nbsp;readonly&nbsp;ImmutableList<object[]>&nbsp;AddressTestCases&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;ImmutableList.Create(new&nbsp;object[]&nbsp;{&nbsp;"",&nbsp;false&nbsp;},&nbsp;new&nbsp;object[]&nbsp;{&nbsp;"testtest",&nbsp;true&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP