c# – 用于将对象添加到对象初始化程序中的集合的语法糖

最近,我遇到了一些看起来像这样的代码
public class Test
{
    public ICollection<string> Things { get; set; }

    public test()
    {
        Things = new List<string> { "First" };
    }

    public static Test Factory()
    {
        return new Test
        {
            Things = { "Second" }
        };
    }
}

调用Test.Factory()会导致Test对象具有包含“First”和“Second”的Things集合.

它看起来像是Things = {“Second”}行调用了物种的Add方法.如果ICollection更改为IEnumerable,则会出现语法错误,指出“IEnumerable< string>不包含’Add’的定义”.

很明显,您只能在对象初始化器中使用这种语法.这样的代码无效:

var test = new test();
test.Things = { "Test" };

这个功能名称是什么?它引入了哪个版本的C#?为什么它只在对象初始化器中可用?

解决方法

它被称为 collection initializer,它被添加C# 3 language specifications(引言中的第7.5.10.3节,当前规范中的第7.6.10.3节).具体而言,您使用的代码使用嵌入式集合初始值设定项.

集合初始化程序实际上只是调用Add方法,这是根据规范要求的.

正如Quantic评论的那样,规格说:

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property,the elements given in the initializer are added to the collection referenced by the field or property.

这解释了你意想不到的结果非常好.

Why is it only available in object initialisers?

因为它在其他地方没有意义.你可以自己调用Add方法,而不是使用初始化器而不是初始化.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...