最近,我遇到了一些看起来像这样的代码:
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" }
};
}
}
Run Code Online (Sandbox Code Playgroud)
调用带有包含和的集合Test.Factory()的Test对象的结果.Things"First""Second"
看起来该行Things = { "Second" }调用了Add方法Things.如果ICollection更改为a IEnumerable,则表示语句错误" IEnumerable<string> does not contain a definition for 'Add'".
很明显,您只能在对象初始化器中使用这种语法.这样的代码无效:
var test = new Test();
test.Things = …Run Code Online (Sandbox Code Playgroud)