C#向List中添加项目

3

我正在尝试使用以下代码向列表中添加项目:

public class Reason
{
    [JsonProperty("code")]
    public int Code { get; internal set; }
}

public class Item
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("quantity")]
    public int quantity { get; set; }

    [JsonProperty("reason")]
    public Reason reason { get; set; } = new Reason();
}

public class RootObject
{
    [JsonProperty("dropOff")]
    public DropOff dropOff { get; set; } = new DropOff();

    [JsonProperty("providerId")]
    public int providerId { get; set; }

    [JsonProperty("orderReference")]
    public string orderReference { get; set; }

    [JsonProperty("returnMethodId")]
    public int returnMethodId { get; set; }

    [JsonProperty("items")]
    public List<Item> items { get; set; } = new List<Item>();
}


root.items.Add(new Item { Id = 8675072, quantity = 1, Reason.Code = 2  });

尝试添加 Reason.Code 时,我遇到了如下错误:

对于非字段、方法或属性,需要对象引用。

我需要在哪里初始化才能将 Reason.Code 添加到列表中?


你能展示一下在哪里初始化了 root 吗? - Sean
什么是根? - Ali Beyit
你是在类外尝试向“root”添加项目吗? - SᴇM
1个回答

0
root.items.Add(new Item { Id = 8675072, quantity = 1, reason = { Code = 2  }})

这个= { SomeProperty = value }部分叫什么?它看起来像属性初始化器,但我确定它只能与new一起使用。 - Sinatr
@Sinatr 请参考 https://dev59.com/jGQn5IYBdhLWcg3we3LD - Matthew Watson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接