【问题标题】:C# adding items to ListC# 将项目添加到列表
【发布时间】:2020-06-23 08:49:13
【问题描述】:

我正在尝试使用以下内容将项目添加到列表中;

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
  • 什么是根???
  • 您是否要在课堂外向root 添加项目?

标签: c# arrays list methods initialization


【解决方案1】:
root.items.Add(new Item { Id = 8675072, quantity = 1, reason = { Code = 2  }})

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多