c# - 在 C# 中初始化一个 Generic.List

标签 c# .net generics constructor

在 C# 中,我可以使用以下语法初始化列表。

List<int> intList= new List<int>() { 1, 2, 3 };

我想知道 {} 语法是如何工作的,以及它是否有名称。有一个采用 IEnumerable 的构造函数,您可以调用它。

List<int> intList= new List<int>(new int[]{ 1, 2, 3 });

这似乎更“标准”。当我解构列表的默认构造函数时,我只看到

this._items = Array.Empty;

我希望能够做到这一点。

CustomClass abc = new CustomClass() {1, 2, 3};

并能够使用 1, 2, 3 列表。这是如何工作的?

更新

乔恩斯基特回答

It's calling the parameterless constructor, and then calling Add:

> List<int> tmp = new List<int>();
> tmp.Add(1); tmp.Add(2); tmp.Add(3);
> List<int> intList = tmp;

我明白是做什么的。我想知道怎么做。该语法如何知道调用 Add 方法?

更新

我知道,接受 Jon Skeet 的回答是多么陈词滥调。但是,带有字符串和整数的示例很棒。还有一个非常有用的 MSDN 页面是:

最佳答案

这称为集合初始化器。它调用无参数构造函数,然后调用 Add:

List<int> tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> intList = tmp;

类型的要求是:

  • 它实现了IEnumerable
  • 它有适合您提供的参数类型的 Add 重载。您可以在大括号中提供多个参数,在这种情况下,编译器会查找具有多个参数的 Add 方法。

例如:

public class DummyCollection : IEnumerable
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new InvalidOperationException("Not a real collection!");
    }

    public void Add(string x)
    {
        Console.WriteLine("Called Add(string)");
    }

    public void Add(int x, int y)
    {
        Console.WriteLine("Called Add(int, int)");
    }
}

然后您可以使用:

DummyCollection foo = new DummyCollection
{
    "Hi",
    "There",
    { 1, 2 }
};

(当然,通常您希望您的集合正确实现 IEnumerable...)

关于c# - 在 C# 中初始化一个 Generic.List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751990/

相关文章:

c# - DataGridView Winforms 填充 ComboBoxCell

javascript - Visual Studio 2015 CTP 在 javascript 编辑器上卡住

.net - 如何在使用 Office 2003 打开 Office 2007 文档时禁用转换消息?

java - 返回类型泛型

java - 自定义对象列表作为泛型方法的参数

c# - 您知道执行此 "massive"linq 过滤的另一种方法吗?

c# - 处理泛型和静态类型之间的交互

java - 在编译时获取泛型类

c# - 在基类对象上使用子类方法

.net - 在 .NET 4.0 中解析无效 HTML 的 XPath?