在 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 });
我想对 Dictionary 做同样的事情。我知道您可以像这样在 C# 3.0 及更高版本中轻松完成此操作:
Dictionary<int, int> d = new Dictionary<int, int> { { 0, 1 }, { 1, 2 }, { 2, 3 } };
但它在 C# 2.0 中不起作用。在不使用 Add
或基于现有集合的情况下,是否有任何解决方法?
最佳答案
But it doesn't work in C# 2.0. Is there any workaround for this without using Add or basing on an already existing collection?
没有。我能想到的最接近的方法是编写您自己的 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();
这至少仍然是一个单个表达式,这对于您想要在声明点初始化的字段很有用。
关于c# - 在 C# 2.0 中使用值初始化字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17739060/