2012-03-05 55 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