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
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; }
}
最佳答案
Collection Initializers 只允许您赋值到对象的属性或字段。您不能像通常在代码的其他地方那样访问对象初始值设定项中对象属性的成员。另外,即使您有该选项,该列表也未初始化,因此您无法调用 .Add()
方法。
相反,您可以使用集合初始化器来初始化列表,这样您就可以一次性直接将 IntDto
项添加到列表中:
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 }
};
}
引用资料:
关于c# - 使用对象初始值设定项时如何向列表添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513225/