为什么我可以像 C# 中的数组一样初始化 List? [英] Why can I initialize a List like an array in C#?

查看:43
本文介绍了为什么我可以像 C# 中的数组一样初始化 List?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Today I was surprised to find that in C# I can do:

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

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

Why can I do this? What constructor is called? How can I do this with my own classes? I know that this is the way to initialize arrays but arrays are language items and Lists are simple objects ...

推荐答案

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

This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:

  • 它实现了IEnumerable(最好是IEnumerable)

它有一个名为Add(...)

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

What happens is the default constructor is called, and then Add(...) is called for each member of the initializer.

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

Thus, these two blocks are roughly identical:

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> 过大等:

You can call an alternate constructor if you want, for example to prevent over-sizing the List<T> during growing, etc:

// 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() 方法不必采用单个项目,例如 DictionaryAdd() 方法code> 需要两个项目:

Note that the Add() method need not take a single item, for example the Add() method for Dictionary<TKey, TValue> takes two items:

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)并创建一个或更多 Add() 方法:

So, to add this to your own class, all you need do, as mentioned, is implement IEnumerable (again, preferably IEnumerable<T>) and create one or more Add() methods:

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 集合一样使用它:

Then you can use it just like the BCL collections do:

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

    // ...
}

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

(For more information, see the MSDN)

这篇关于为什么我可以像 C# 中的数组一样初始化 List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆