C#如何将List作为type属性设置为其他类

时间:2018-03-23 14:22:32

标签: c# list class properties

我有两节课。第一类是“StoreList”:

class StoreList
{
    public string Code { get; set; }
    public string Name { get; set; }
    public int StoreId { get; set; }
}

其次是DataList:

class DataList
{
    public List<StoreList> StoreListData { get; set; } //I don't know if this is correct
}

所以我可以在这样的代码中使用:

var liststoreIds = client.storeList(sessionId); //here I get data from API, all ok

var storeList = new DataList();

foreach (var stores in liststoreIds)
{
    storeList.StoreListData.Add(new StoreList
    {
         Code = stores.code,
         Name = stores.name,
         StoreId = stores.store_id
    });
}

在代码中我收到错误:“对象引用未设置为对象的实例。”哪里有问题?

1 个答案:

答案 0 :(得分:2)

您必须在构造函数或内联中​​初始化列表:

class DataList
{
    public List<StoreList> StoreListData { get; set; } = new List<StoreList>();
}
相关问题