在自定义类上创建字典样式集合初始值设定项

可能重复:
自定义集合初始化器

我有一个简单的Pair类:

public class Pair { 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[] { {0, "bob"}, {1, "phil"}, {0, "nick"} }; 

但它要求我定义一个全新的Pair(0,“bob”)等,我将如何实现它?

像往常一样,谢谢你们!

要使自定义初始化像Dictionary一样工作,您需要支持两件事。 您的类型需要实现IEnumerable并具有适当的Add方法。 您正在初始化一个没有Add方法的Array 。 例如

 class PairList : IEnumerable { private List> _list = new List>(); public void Add(T1 arg1, T2 arg2) { _list.Add(new Pair(arg1, arg2)); } IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } } 

然后你就可以做到

 var temp = new PairList { {0, "bob"}, {1, "phil"}, {0, "nick"} }; 

为什么不使用inheritance自Dictionary的类?

 public class PairDictionary : Dictionary { } private static void Main(string[] args) { var temp = new PairDictionary { {0, "bob"}, {1, "phil"}, {2, "nick"} }; Console.ReadKey(); } 

您也可以创建自己的集合(我怀疑是这种情况,因为您对两个项目具有相同的Value1 ,因此T1不作为示例中的键)不从Dictionaryinheritance。

如果你想使用集合初始化程序的语法糖,你必须提供一个带有2个参数的Add方法(在你的情况下, T1T2intstring )。

 public void Add(int value1, string value2) { } 

请参阅自定义集合初始化器

 public class Paircollection : List> { public void Add(T1 value1, T2 value2) { Add(new Pair(value1, value2)); } } 

然后

 var temp = new Paircollection { {0, "bob"}, {1, "phil"}, {0, "nick"} }; 

将工作。 基本上你只是创建一个List> ,知道如何正确添加东西。

这显然可以扩展到除Pair之外的任何其他类(以字典解决方案不是这样的方式)。

感谢Yuriy Faktorovich帮助我完成了我最初的理解和相关的问题,指出了我正确的方向。

您正在寻找的语法不是由与字典一起使用的对象提供的,而是字典集合本身。 如果您需要能够使用集合初始化程序,那么您将需要使用现有集合(如Dictionary)或实现自定义集合来容纳它。

否则你基本上只限于:

 var temp = new Pair[] { new Pair(0, "bob"), new Pair(1, "phil"), new Pair(0, "nick") };