簡體   English   中英

使用C#2.0中的值初始化Dictionary

[英]Initialize a Dictionary with values in C# 2.0

在C#2.0中,我們可以使用以下值來初始化數組和列表:

int[] a = { 0, 1, 2, 3 };
int[,] b = { { 0, 1 }, { 1, 2 }, { 2, 3 } };
List<int> c = new List<int>(new int[] { 0, 1, 2, 3 });

我想對字典做同樣的事情。 我知道你可以在C#3.0之后輕松完成這樣的事情:

Dictionary<int, int> d = new Dictionary<int, int> { { 0, 1 }, { 1, 2 }, { 2, 3 } };

但它在C#2.0中不起作用。 有沒有使用Add或基於現有集合的解決方法?

但它在C#2.0中不起作用。 有沒有使用添加或基於現有集合的解決方法?

不。我能想到的最接近的是編寫自己的DictionaryBuilder類型以使其更簡單:

public class DictionaryBuilder<TKey, TValue>
{
    private Dictionary<TKey, TValue> dictionary
        = new Dictionary<TKey, TValue> dictionary();

    public DictionaryBuilder<TKey, TValue> Add(TKey key, TValue value)
    {
        if (dictionary == null)
        {
            throw new InvalidOperationException("Can't add after building");
        }
        dictionary.Add(key, value);
        return this;
    }

    public Dictionary<TKey, TValue> Build()
    {
        Dictionary<TKey, TValue> ret = dictionary;
        dictionary = null;
        return ret;
    }
}

然后你可以使用:

Dictionary<string, int> x = new DictionaryBuilder<string, int>()
    .Add("Foo", 10)
    .Add("Bar", 20)
    .Build();

這至少是一個表達式 ,對於要在聲明點初始化的字段很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM