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

标签 c# object .net-core generic-collections

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/

相关文章:

c# - 如何返回能够在服务器上执行的对象?

javascript - 将 JSON 插入 MongoDB 自动从字符串转换日期

javascript - 如何访问被重写的对象的内置方法?

.net - .NET Core 2.0 有 SFTP 客户端吗?

C# 将源文件编译为插件

c# - 从数组中删除一项并将其他项向后移动

c# - Teamcity、Sonar 和 C#/.NET

java - 无法将一个类的对象访问到另一个类中

asp.net-core - InvalidOperationException 在强类型 View 中呈现 ViewComponent

c# - Blazor 处理来自 Web Api 的响应中的错误