【问题标题】:ImmutableList does not contain a constructor that takes 0 argumentsImmutableList 不包含采用 0 个参数的构造函数
【发布时间】:2018-06-12 15:06:11
【问题描述】:

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

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

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

【问题讨论】:

  • 您做错的是使用不存在的构造函数。将列表中所需的一组对象传递给构造函数。
  • 如果构造函数不存在,如何传递一组对象给它?它也不适用于 1 个参数、2 个等。它会引发同样的错误。
  • 就像错误状态一样,ImmutableList does not contain a constructor that takes 0 arguments。您需要使用带有一个参数的构造函数,即带有对象列表的构造函数。
  • ImmutableList does not contain a constructor that takes 1 arguments 然后我得到这个错误,我尝试只是通过null

标签: c# immutable-collections


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    您将需要使用其中一种构建器方法:

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

    【讨论】:

    【解决方案3】:

    要创建 ImmutableList,您必须使用在 ImmutableList 静态类上定义的静态工厂方法 Create()。

    这意味着你需要

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

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多