IDictionary赋值快捷键编译器功能或语言功能?

Bui*_*ted 4 .net c# compiler-construction

通过今天的一些随机对象创建,我遇到了这个简洁的小捷径Dictionary<K, V>.以下分配是编译器快捷方式还是它的一个功能Dictionary<string, string>.

IDictionary<string, string> items = { { "item1key", "item1value" } };
Run Code Online (Sandbox Code Playgroud)

看看源代码Dictionary<K, V>我没有看到任何关于它是如何工作的.实现此类点的所有接口不允许我执行类似的操作.为什么我们可以为字典而不是其他类型.例如,编译器或语言功能如何知道第一项是键,第二项是值.或者甚至更具体地说,这个相同的语法不能用于aList<string>

List<string> items = { "item1" };
Run Code Online (Sandbox Code Playgroud)

所以第一个是有效的,为什么?

我不一定试图复制这个,而是好奇为什么它是这样的.在这种情况下,什么使字典特别?

有效的例子

public class Button
{
    public string Title { get; set; }
    public ButtonType Type { get; set; }
    public IDictionary<string, string> Items { get; set; }
    public bool RequiresSelected { get; set; }
}

var buttons = new List<Button>
    {
        new Button { 
            Items = {
                        {"button1", "Button 1"},
                        {"button2", "Button 2"},
                        {"button3", "Button 3"},
                    }, 
            Title = "3 Buttons", 
            Type = ButtonType.DropDown 
        }
    };
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

您显示的语法在C#中无效.你需要:

IDictionary<string, string> items = new Dictionary<string, string>
    { { "item1key", "item1value" } };
Run Code Online (Sandbox Code Playgroud)

那时它只是一个普通的集合初始值设定项,因此列表等价物将是:

List<string> items = new List<string> { "item1" };
Run Code Online (Sandbox Code Playgroud)

编辑:让我们看看我的编辑是否可以击败你的.我的猜测是你看过类似的东西:

var foo = new Foo {
    SomeDictionaryProperty = { 
         { "item1key", "item1value" }
    }
};
Run Code Online (Sandbox Code Playgroud)

这是一个嵌入式集合初始化程序,也可以用于列表.它不是创建一个词典,而是添加到现有词典中.上面的代码相当于:

var tmp = new Foo();
tmp.SomeDictionaryProperty.Add("item1key", "item1value");
var foo = tmp;
Run Code Online (Sandbox Code Playgroud)

它的另一个例子是:

var form = new Form {
    Controls = { new Label { Text = "Foo"}, new Label { Text = "Bar" } }
};
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见C#4规范(对象初始化程序)的7.6.10.2节.重要的是这个:

member-initializer:
    identifier   =   initializer-value

initializer-value:
    expression
    object-or-collection-initializer
Run Code Online (Sandbox Code Playgroud)

所以可以将属性初始化为要么是一个特定值(在这种情况下,设定部将被使用)经由对象/集合初始化,在这种情况下,吸气剂的属性将被使用,然后制定者或添加方法将用于对象/集合初始化程序的主体.