可能重复:
自定义集合初始化程序
我有一个简单的Pair类:
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对象一样定义它,所有的内联都是这样的:
var temp = new Pair<int, string>[]
{
{0, "bob"},
{1, "phil"},
{0, "nick"}
};
但它要求我定义一个全新的Pair(0,"bob")等,我该如何实现?
像往常一样,谢谢大家!
要使自定义初始化像Dictionary一样工作,需要支持两件事。您的类型需要实现IEnumerable
并具有适当的Add
方法。您正在初始化一个没有Add
方法的Array
。例如
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
继承的类?
public class PairDictionary : Dictionary<int, string>
{
}
private static void Main(string[] args)
{
var temp = new PairDictionary
{
{0, "bob"},
{1, "phil"},
{2, "nick"}
};
Console.ReadKey();
}
您也可以创建自己的集合(我怀疑是这样,因为您对两个项目有相同的Value1
,所以T1
在您的示例中不充当键),这些集合不是从Dictionary
继承的。
如果你想使用集合初始值设定项的语法糖,你必须提供一个Add
方法,它接受2个参数(T1
和T2
,在你的例子中是int
和string
)。
public void Add(int value1, string value2)
{
}
请参阅自定义集合初始化程序
public class Paircollection<T1, T2> : List<Pair<T1, T2>>
{
public void Add(T1 value1, T2 value2)
{
Add(new Pair<T1, T2>(value1, value2));
}
}
然后
var temp = new Paircollection<int, string>
{
{0, "bob"},
{1, "phil"},
{0, "nick"}
};
将起作用。从本质上讲,您只是在创建一个List<Pair<T1,T2>>
版本,它知道如何做正确的Add事情。
这显然可以扩展到Pair之外的任何其他类(在某种程度上,字典解决方案不是这样)。
感谢Yuriy Faktorovich帮助我初步理解并提出相关问题,为我指明了正确的方向。
您要查找的语法不是由与字典一起使用的对象提供的,而是字典集合本身。如果您需要能够使用集合初始值设定项,则需要使用现有集合(如Dictionary)或实现自定义集合来容纳它。
否则,你基本上只限于:
var temp = new Pair<int, string>[]
{
new Pair(0, "bob"),
new Pair(1, "phil"),
new Pair(0, "nick")
};