C#初始化列表属性[重复]

问题描述 投票:0回答:1

我有以下包含列表的课程

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

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

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

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

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

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

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

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

我想在列表中添加项目,这是我在其他班级所做的;

        Booking.RootObject root = new Booking.RootObject();
        root.providerId = 111;
        root.Reference = "ytrhtew";
        root.returnMethodId = 1;
        root.items.Add(new Item { variantId = 1, quantity = 1, returnReason = 2 });

由于以下原因而失败-对象引用未设置为对象的实例

我将需要对其进行初始化才能使其正常工作,以便可以将项目添加到列表中?

c# list testing initialization poco
1个回答
-2
投票

您缺少列表的Items属性。

root.items.Items.Add(new Item { variantId = 1, quantity = 1, returnReason = 2 }); 
© www.soinside.com 2019 - 2024. All rights reserved.