同时将对象添加到具有属性的列表中

sim*_*ada 3 c#

我有,

List<Items> itemDetails = new List<Item>();
itemDetails.Add(new Item { isNew = true, Description = "test description" });
Run Code Online (Sandbox Code Playgroud)

为什么我不能写上面的代码

List<Items> itemDetails = new List<Item>().Add(new Item { isNew = true, Description = "test description" });
Run Code Online (Sandbox Code Playgroud)

它给出了错误

Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

当你打电话时Add,它有一个void返回类型......这就是你得到错误的原因.表达式的总体结果new List<Item>().Add(...)void.

但是,您可以使用集合初始值设定项:

List<Item> itemDetails = new List<Item>
{
    new Item { isNew = true, Description = "test description" },
    new Item { isNew = false, Description = "other description" }
};
Run Code Online (Sandbox Code Playgroud)

这基本上告诉编译器将集合初始化程序中的每个元素转换Add为对您的调用.