c# - IDictionary 分配快捷方式编译器功能或语言功能?

标签 c# .net compiler-construction

通过今天的一些随机对象创建,我遇到了一个 Dictionary<K, V> 的简洁小快捷方式.以下赋值是编译器快捷方式还是 Dictionary<string, string> 的一个特性? .

IDictionary<string, string> items = { { "item1key", "item1value" } };

查看 Dictionary<K, V> 的来源我没有立即看到它是如何工作的。实现此类的所有接口(interface)不允许我执行类似的操作。为什么我们可以为字典做这件事而不是其他类型。例如,编译器或语言功能如何知道第一项是键,第二项是值。或者更具体地说,同样的语法不能用于 List<string>

List<string> items = { "item1" };

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

我不一定要复制它,而是很好奇为什么它是这样的。在这种情况下,字典有什么特别之处?

有效的例子

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 
        }
    };

最佳答案

您展示的语法在 C# 中无效。你需要:

IDictionary<string, string> items = new Dictionary<string, string>
    { { "item1key", "item1value" } };

那时它只是一个普通的集合初始化器,所以等价的列表是:

List<string> items = new List<string> { "item1" };

编辑:让我们看看我的编辑能否打败您的。我的猜测是您已经看到类似的内容:

var foo = new Foo {
    SomeDictionaryProperty = { 
         { "item1key", "item1value" }
    }
};

这是一个嵌入式 集合初始值设定项,也可用于列表。它不是创建 字典,而是添加到现有字典中。上面的代码等价于:

var tmp = new Foo();
tmp.SomeDictionaryProperty.Add("item1key", "item1value");
var foo = tmp;

它工作的另一个例子:

var form = new Form {
    Controls = { new Label { Text = "Foo"}, new Label { Text = "Bar" } }
};

有关详细信息,请参阅 C# 4 规范(对象初始值设定项)的第 7.6.10.2 节。重要的一点是:

member-initializer:
    identifier   =   initializer-value

initializer-value:
    expression
    object-or-collection-initializer

因此您可以通过对象/集合初始化器或者将属性初始化为特定值(在这种情况下将使用 setter),在这种情况下将使用属性的 getter,然后将 setter 或 Add 方法用于对象/集合初始值设定项的主体。

关于c# - IDictionary 分配快捷方式编译器功能或语言功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439068/

相关文章:

c# - Asp.net Core Post 参数始终为 null

c# - 使用 C# 检查用户是否已存在于 MySql 数据库中

c# - 使用 Assembly.Load(path) 时找不到文件或程序集

c - 包含的头文件是否在C文件中展开

c# - C# 中算术溢出检查的最佳实践是什么?

compiler-construction - 如何在 LLVM 中声明全局变量?

c# - Windows 10通用应用程序,访问我的设备信息时抛出异常: 'System.UnauthorizedAccessException' in app. exe?

c# - 使用 async/await 对大型 C# 应用程序进行多线程处理

c# - 使用 Razor 在 MVC 中发布复杂对象列表

c# - DDD 上的免费视频(截屏视频、网络广播...)培训