[英]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.