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

标签 c#

我有,

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

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

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

报错

Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<>

最佳答案

当您调用 Add 时,它有一个 void返回类型...这就是您收到错误的原因。表达式的整体结果 new List<Item>().Add(...)void .

但是,您可以使用 collection initializer :

List<Item> itemDetails = new List<Item>
{
    new Item { isNew = true, Description = "test description" },
    new Item { isNew = false, Description = "other description" }
};

这基本上是告诉编译器将集合初始值设定项中的每个元素转换为 Add。呼唤你。

关于c# - 同时将对象添加到具有属性的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33969776/

相关文章:

c# - 向事件处理函数发送额外的字符串

C# Labels TextAlign 在 OnPaint 覆盖后不起作用

c# - command.ExecuteReader() 抛出异常

c# - 使用 ".*"和 $1 用正则表达式替换文本

c# - 无法从我的 .Net Web 服务返回对象

C# 将个人字体包含到程序中

C#,模运算给出与计算器不同的结果

c# - 使用 autofac 3.1.1 进行属性注入(inject)

c# - 为什么不调用OnDrop? (统一)

c# - 如何为方法设置超时