如何使内联数组初始化像例如字典初始化

如何使内联数组初始化像例如字典初始化

本文介绍了如何使内联数组初始化像例如字典初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么可以这样初始化Dictionary<T1,T2>:

Why is it possible to initialize a Dictionary<T1,T2> like this:

var dict = new Dictionary<string,int>() {
    { "key1", 1 },
    { "key2", 2 }
};

...但是不能以完全相同的方式初始化KeyValuePair<T1,T2>对象的数组:

...but not to initialize, say, an array of KeyValuePair<T1,T2> objects in exactly the same way:

var kvps = new KeyValuePair<string,int>[] {
    { "key1", 1 },
    { "key2", 2 }
};
// compiler error: "Array initializers can only be used in a variable
// or field initializer.  Try using a new expression instead."

我意识到我可以通过为每个项目写new KeyValuePair<string,int>() { "key1", 1 }等使第二个示例工作.但是我想知道是否有可能使用与第一个示例中相同的简洁语法.

I realize that I could make the second example work by just writing new KeyValuePair<string,int>() { "key1", 1 }, etc for each item. But I'm wondering if it's possible to use the same type of concise syntax that is possible in the first example.

如果不可能,那么 Dictionary 类型为何如此特别?

If it is not possible, then what makes the Dictionary type so special?

推荐答案

将集合初始值设定项语法转换为具有适当数量参数的对Add的调用:

The collection initializer syntax is translated into calls to Add with the appropriate number of parameters:

var dict = new Dictionary<string,int>();
dict.Add("key1", 1);
dict.Add("key2", 2);

此特殊的初始化程序语法也可用于具有Add方法并实现IEnumerable的其他类.让我们创建一个完全疯狂的类,只是为了证明Dictionary没有什么特别的,并且该语法可以用于任何合适的类:

This special initializer syntax will also work on other classes that have an Add method and implements IEnumerable. Let's create a completely crazy class just to prove that there's nothing special about Dictionary and that this syntax can work for any suitable class:

// Don't do this in production code!
class CrazyAdd : IEnumerable
{
    public void Add(int x, int y, int z)
    {
        Console.WriteLine(x + y + z); // Well it *does* add...
    }

    public IEnumerator GetEnumerator() { throw new NotImplementedException(); }
}

现在您可以这样写:

var crazyAdd = new CrazyAdd
{
    {1, 2, 3},
    {4, 5, 6}
};

输出:

6
15

查看其在线运行情况: ideone

See it working online: ideone

关于您询问的其他类型:

As for the other types you asked about:

  • 它在数组上不起作用,因为它没有Add方法.
  • List<T>具有Add方法,但只有一个参数.
  • It doesn't work on an array because it has no Add method.
  • List<T> has an Add method but it has only one parameter.

这篇关于如何使内联数组初始化像例如字典初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:31