C# 使用对象初始值设定项时如何向列表中添加值?
当我们看到C# 使用对象初始值设定项时如何向列表中添加值?,c#,object,.net-core,generic-collections,C#,Object,.net Core,Generic Collections,当我们看到PostDto private PostDto MapIntegration(IntDto integ) { return new PostDto { prop1 = "7", prop2 = "10", prop3 = true, prop4 = "EA Test", product_list.Add(integ) // ERROR This says the name product_l
PostDto
private PostDto MapIntegration(IntDto integ)
{
return new PostDto
{
prop1 = "7",
prop2 = "10",
prop3 = true,
prop4 = "EA Test",
product_list.Add(integ) // ERROR This says the name product_list does not exist in current context
};
}
公共类PostDto
{
公共字符串prop1{get;set;}
公共字符串prop2{get;set;}
公共bool prop3{get;set;}
公共字符串prop4{get;set;}
公共列表产品_列表{get;set;}
}
产品列表未初始化
public class PostDto
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public bool prop3 { get; set; }
public string prop4 { get; set; }
public List<IntDto> product_list { get; set; }
}
private PostDto-map集成(IntDto-integ)
{
var ret=新列表();
ret.Add(整数);
返回新的PostDto
{
prop1=“7”,
prop2=“10”,
prop3=正确,
prop4=“EA测试”,
产品列表=ret
};
}
构造一个临时列表或其他可以使用的内容。集合初始值设定项仅允许您为对象的属性或字段赋值。您不能像在代码的其他地方一样,在对象初始值设定项中访问对象属性的成员。另外,即使您有该选项,列表甚至没有初始化,因此您无法调用
.Add()
方法
相反,您可以使用集合初始值设定项初始化列表,以便可以一次性直接将IntDto
项添加到列表中:
private PostDto MapIntegration(IntDto integ)
{
var ret = new List<IntDto>();
ret.Add(integ);
return new PostDto
{
prop1 = "7",
prop2 = "10",
prop3 = true,
prop4 = "EA Test",
product_list = ret
};
}
private PostDto-map集成(IntDto-integ)
{
返回新的PostDto
{
prop1=“7”,
prop2=“10”,
prop3=正确,
prop4=“EA测试”,
//使用集合初始值设定项创建新列表。
product_list=新列表(){integ}
};
}
参考资料:
private PostDto MapIntegration(IntDto integ)
{
return new PostDto
{
prop1 = "7",
prop2 = "10",
prop3 = true,
prop4 = "EA Test",
// Create a new list with collection initializer.
product_list = new List<IntDto>() { integ }
};
}