加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:09:46 所属栏目:百科 来源:网络整理
导读:最近,我遇到了一些看起来像这样的代码: public class Test{ public ICollectionstring Things { get; set; } public Test() { Things = new Liststring { "First" }; } public static Test Factory() { return new Test { Things = { "Second" } }; }} 调用
最近,我遇到了一些看起来像这样的代码:
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方法,而不是使用初始化器而不是初始化.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读