相关疑难解决方法(0)

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

最近,我遇到了一些看起来像这样的代码:

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)

c# syntax

7
推荐指数
1
解决办法
312
查看次数

标签 统计

c# ×1

syntax ×1