自定义集合初始化 [英] Custom Collection Initializers
问题描述
实现类的IEnumerable
并提供了公共无效添加(/ * ARGS * /)
函数可以初始化像在下面的示例:
Classes that implement IEnumerable
and provide a public void Add(/* args */)
function can be initialized like in the following example:
List<int> numbers = new List<int>{ 1, 2, 3 };
这初始化列表℃之后调用
添加(INT)
函数的3倍; INT方式&gt;
which calls the Add(int)
function 3x after initializing the List<int>
.
有没有办法来明确定义我自己的类这种行为?例如,我可以初始化比调用合适的以外的功能添加()
超载?
Is there a way to define this behavior explicitly for my own classes? For example, could I have the initializer call a function other than the appropriate Add()
overload?
推荐答案
没有,编译器需要一个命名的方法添加
的集合初始化工作。这是在C#规范定义,不能改变:
No, the compiler requires a method named Add
for the collection initializer to work. This is defined in C# specification and cannot be changed:
要应用集合初始化集合对象必须是实现 System.Collections.IEnumerable
或发生编译时错误的类型。因为,为了每一个指定的元素,集合初始值调用一个添加
法元素初始化为参数列表的前pression列表中的目标对象上,应用正常超载对于每次调用分辨率。因此, 集合对象必须包含一个适用添加
方法的的每个元素初始化。 [重点煤矿] 的
C# Language Specification - 7.5.10.3 Collection Initializers
The collection object to which a collection initializer is applied must be of a type that implements
System.Collections.IEnumerable
or a compile-time error occurs. For each specified element in order, the collection initializer invokes anAdd
method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicableAdd
method for each element initializer. [emphasis mine]
当然,添加
方法可以使用多个参数(如词典&LT; TKEY的,TValue&GT;
)
Of course, the Add
method can take more than one argument (like Dictionary<TKey, TValue>
):
dic = new Dictionary<int, int> {
{ 1, 2 },
{ 3, 4 }
};
// translated to:
dic = new Dictionary<int, int>();
dic.Add(1, 2);
dic.Add(3, 4);
这篇关于自定义集合初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!