在自定义类上创建Dictionary-style集合初始值设定项 [英] Create Dictionary-style collection initializer on custom class
问题描述
可能重复:
自定义集合初始化器
Possible Duplicate:
Custom Collection Initializers
我有一个简单的Pair类:
I have a simple Pair class:
public class Pair<T1, T2>
{
public Pair(T1 value1, T2 value2)
{
Value1 = value1;
Value2 = value2;
}
public T1 Value1 { get; set; }
public T2 Value2 { get; set; }
}
并且希望能够像Dictionary对象一样定义它,所有内联都是这样:
And would like to be able to define it like a Dictionary object, all inline like so:
var temp = new Pair<int, string>[]
{
{0, "bob"},
{1, "phil"},
{0, "nick"}
};
但是它要我定义一个全新的Pair(0,"bob")等,我将如何实现呢?
But it is asking me to define a full new Pair(0, "bob") etc, how would I implement this?
像往常一样,谢谢大家!
As usual, thanks guys!
推荐答案
要使自定义初始化像Dictionary一样工作,您需要支持两件事.您的类型需要实现IEnumerable
并具有适当的Add
方法.您正在初始化一个Array
,它没有Add
方法.例如
To get the custom initialization to work like Dictionary you need to support two things. Your type needs to implement IEnumerable
and have an appropriate Add
method. You are initializing an Array
, which doesn't have an Add
method. For example
class PairList<T1, T2> : IEnumerable
{
private List<Pair<T1, T2>> _list = new List<Pair<T1, T2>>();
public void Add(T1 arg1, T2 arg2)
{
_list.Add(new Pair<T1, T2>(arg1, arg2));
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}
然后您就可以
var temp = new PairList<int, string>
{
{0, "bob"},
{1, "phil"},
{0, "nick"}
};
这篇关于在自定义类上创建Dictionary-style集合初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!