我为什么能像初始化在C#中的数组列表? [英] Why can I initialize a List like an array in C#?
问题描述
今天,我很惊讶地发现,在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
(preferably的IEnumerable&LT; T&GT;
)
It implements
IEnumerable
(preferablyIEnumerable<T>
)
它有一个名为方法添加(...)
会发生什么事是默认的构造函数被调用,然后添加(...)
被调用初始化的每一个成员。
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;
您可以拨打一个可选的构造,如果你想,例如,prevent过大小的名单,其中,T&GT;
中成长等:
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, }
请注意,添加()
方法不必采取一个单一的项目,例如添加()
方法为词典&LT; TKEY的,TValue&GT;
有两个项目:
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 }
};
大致相同的:
Is roughly identical to:
var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;
所以,把它添加到自己的类,你需要做的,如前所述,是贯彻的IEnumerable
(同样,preferably IEnumerable的&LT; T&GT;
),并创建一个或多个添加()
方法:
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 )
这篇关于我为什么能像初始化在C#中的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!