最近,我遇到了一些看起来像这样的代码:
@H_404_2@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’的定义”.
很明显,您只能在对象初始化器中使用这种语法.这样的代码无效:
@H_404_2@var test = new Test(); test.Things = { "Test" };解决方法
它被称为
collection initializer,它被添加到
C# 3 language specifications(引言中的第7.5.10.3节,当前规范中的第7.6.10.3节).具体而言,您使用的代码使用嵌入式集合初始值设定项.
集合初始化程序实际上只是调用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?