c# - 为什么我可以在 C# 中像数组一样初始化一个列表?

标签 c# .net list initialization

今天我惊讶地发现在 C# 中我可以做到:

List<int> a = new List<int> { 1, 2, 3 };

为什么我可以这样做?调用什么构造函数?我怎样才能用我自己的类(class)做到这一点?我知道这是初始化数组的方法,但数组是语言项而列表是简单对象 ...

最佳答案

这是 .NET 中集合初始化器语法的一部分。您可以在您创建的任何集合上使用此语法,只要:

  • 它实现了 IEnumerable (最好是 IEnumerable<T> )

  • 它有一个名为 Add(...) 的方法

会发生什么是调用默认构造函数,然后 Add(...)为初始化程序的每个成员调用。

因此,这两个 block 大致相同:

List<int> a = new List<int> { 1, 2, 3 };

List<int> temp = new List<int>();
temp.Add(1);
temp.Add(2);
temp.Add(3);
List<int> a = temp;

如果需要,您可以调用备用构造函数,例如防止List<T> 过大在生长过程中等:

// Notice, calls the List constructor that takes an int arg
// for initial capacity, then Add()'s three items.
List<int> a = new List<int>(3) { 1, 2, 3, }

请注意 Add()方法不需要采用单个项目,例如 Add() Dictionary<TKey, TValue> 的方法需要两个项目:

var grades = new Dictionary<string, int>
    {
        { "Suzy", 100 },
        { "David", 98 },
        { "Karen", 73 }
    };

大致等同于:

var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;

因此,如前所述,要将其添加到您自己的类中,您需要做的就是实现 IEnumerable (同样,最好是 IEnumerable<T> )并创建一个或多个 Add()方法:

public class SomeCollection<T> : IEnumerable<T>
{
    // implement Add() methods appropriate for your collection
    public void Add(T item)
    {
        // your add logic    
    }

    // implement your enumerators for IEnumerable<T> (and IEnumerable)
    public IEnumerator<T> GetEnumerator()
    {
        // your implementation
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

然后您可以像使用 BCL 集合一样使用它:

public class MyProgram
{
    private SomeCollection<int> _myCollection = new SomeCollection<int> { 13, 5, 7 };    

    // ...
}

(有关详细信息,请参阅 MSDN)

关于c# - 为什么我可以在 C# 中像数组一样初始化一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853937/

相关文章:

c#:在子项上显示工具提示

c# - asp.net中如何在Lucene.net中进行模糊搜索?

c# - 如何减小从 ASP.net 呈现的 html 的大小?

c# - 如何以编程方式在 IIS 8 上设置 App Pool Identity

c++ - 如何从用户那里获取输入并将其推送到列表

c# - Entity Framework 代码优先 : CASCADE DELETE for same table many-to-many relationship

c# - 我如何捕获页面无法加载消息?

.net - Silverlight 3 到 4 风险分析

list - 替换 Haskell 中的单个列表元素?

c# - 如何使结构组件成为变量?