微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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方法,而不是使用初始化器而不是初始化.

原文地址:https://www.jb51.cc/csharp/100945.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐