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" };
解决方法
集合初始化程序实际上只是调用Add方法,这是根据规范要求的.
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?
原文地址:https://www.jb51.cc/csharp/100945.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。