2012-03-05 57 views
15

可能重复:
Custom Collection Initializers定制类创建字典样式集合初始化

我有一个简单的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"} 
     }; 

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

像往常一样,谢谢你们!

+0

好问题!我编辑了你的答案以使用正确的术语(集合初始值设定器)。这通常是在事物的集合方面完成的(它必须有一个Add()方法)。在这种情况下,你正在使用一个数组,所以它不会以相同的方式工作。但非常感兴趣,看看是否有办法让它工作! – MattDavey 2012-03-05 16:35:29

+0

不是'KeyValuePair '的粉丝吗?或者去申请知识? – 2012-03-05 16:37:11

回答

17

为了让自定义初始化像字典工作,你需要支持两件事情。您的类型需要执行IEnumerable,并有适当的Add方法。您正在初始化一个Array,它没有Add方法。例如

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"} 
}; 
+0

你是否暗示'int [] nums = {1,2,3};'是否无效C#?因为它是......当然问题是Pair没有Add方法? – Chris 2012-03-05 16:41:35

+0

@Chris那不像字典。 – 2012-03-05 16:42:37

+0

是的,看得更多,我看到问题出在哪里。我曾经想过,因为语法在我的评论中起作用,问题在于生成Pair对象。在看更多的东西(并试图编写有效的代码来做到这一点)时,我意识到原始帖子使用的语法试图在数组上调用Add(1,“bob”),这就是你所说的'不存在。对不起,我会留下评论,让下一个可怜的傻瓜像我一样思考。 :) – Chris 2012-03-05 16:46:15

6

为什么不使用从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方法,该方法需要两个参数(T1T2这是intstring你的情况)。

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

Custom Collection Initializers

0

你要找的是不是由所用的字典中使用的对象提供的语法,这是字典集合本身。如果您需要能够使用集合初始化程序,那么您需要使用现有的集合(如Dictionary)或实现一个自定义集合来存放它。

否则你基本上限于:

var temp = new Pair<int, string>[] 
    { 
     new Pair(0, "bob"), 
     new Pair(1, "phil"), 
     new Pair(0, "nick") 
    }; 
2
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>>

这显然可以扩展到任何其他类比对(在字典解决方案的方式)。

感谢Yuriy Faktorovich帮助我了解最初的理解和指向正确方向的链接问题。

+1

不好意思,但你不需要'foo',你永远不会使用它。 – 2012-03-05 17:01:05

+0

Pedantry批准并更正。当我使用List作为成员而不是继承时,这是一个宿醉。 :) – Chris 2012-03-05 17:13:13