使用对象初始值设定项时如何向列表添加值?

How to add value to list when using object initializer?

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; }
}

product_list 未初始化。

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
    };
}

构造一个临时列表或其他可以使用的东西。

集合初始化器只允许您赋值给对象的属性或字段。您不能像通常在代码的其他地方那样访问对象初始值设定项中对象的 属性 的成员。另外,即使你有那个选项,列表甚至都没有初始化,所以你不能调用 .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 }
    };
}

参考文献: