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

ImmutableList does not contain a constructor that takes 0 arguments

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

public static readonly ImmutableList<object[]> AddressTestCases = new ImmutableList<object[]>
{
    new object[]{ "", false },
    new object[]{ "testestest", true },
};

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

您使用的语法是而不是调用您认为是的构造函数。它正在调用空构造函数,然后在后台调用您提供的对象数组 .Add

您将需要使用其中一种生成器方法:

public static readonly ImmutableList<object[]> AddressTestCases =
                          new[] {
                                   new object[]{ "", false }, 
                                   new object[]{ "testestest", true }
                                }).ToImmutableList();

好的 ImmutableList 有一个您应该使用的创建方法

public ImmutableList<int> ImmutableListCreate()
{
    return ImmutableList.Create<int>(1, 2, 3, 4, 5);
}

要创建 ImmutableList,您必须使用在 ImmutableList static class.

上定义的静态工厂方法 Create()

这意味着您将需要

public static readonly ImmutableList<object[]> AddressTestCases = 
    ImmutableList.Create(new object[] { "", false }, new object[] { "testtest", true });