c# - 在 C# 2.0 中使用值初始化字典

标签 c# dictionary 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 });

我想对 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/

相关文章:

c# - Silverlight - 如何本地化对 WCF 服务的调用?

c# - 什么是#date# 以及如何转换为 C#?

c# - 在 C# 中打印 Form/UserControl

r - 如何使用 purrr 和 Pipes 顺序应用函数

c# - EditorTemplate 中的 MVC 字典

c# - 加速 File.Exists 用于不存在的网络共享

c# - 实现具有类型约束的通用接口(interface)

c# - 处理服务启动时的异常

java - 在迭代 map 时使用反射

c# - C#中如何在WebBrowser控件中加载本地HTML页面