自定义集合初始化 [英] Custom Collection Initializers

查看:148
本文介绍了自定义集合初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现类的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 an Add 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 applicable Add 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屋!

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