【发布时间】:2022-10-23 12:29:31
【问题描述】:
警告:Customer.Customer() 退出构造函数时,不可为空的属性“CustomerItemList”必须包含非空值。考虑将属性声明为可为空。 如何解决这个问题?
class Customer : Inventory
{
public List<string> CustomerItemList { get; set;} //warning occurred in this line
public List<Customer> getCustomerList(){
List<Customer> customers = new List<Customer>();
List<string> customerItemList1 = new List<string>();
List<string> customerItemList2 = new List<string>();
List<string> customerItemList3 = new List<string>();
customerItemList1.Add("INDHS");
customerItemList1.Add("INOPL");
customerItemList2.Add("INCDS");
customerItemList2.Add("INWSZ");
customerItemList3.Add("INOPL");
customerItemList3.Add("INQAB");
customers.Add(new Customer { CutomerId = "CUABC", CutomerName = "Bala", CustomerItemList = customerItemList1, InventoryQty = 25 });
customers.Add(new Customer { CutomerId = "CUWDZ", CutomerName = "Manju", CustomerItemList = customerItemList2, InventoryQty = 12 });
customers.Add(new Customer { CutomerId = "CUQOP", CutomerName = "Chandru", CustomerItemList = customerItemList3, InventoryQty = 10 });
return customers;
}
}
【问题讨论】:
-
A) 那不是构造函数(没有显示构造函数),B) CustomerItemList 从未初始化,C) Customer 从 Inventory 继承似乎有点奇怪。 D) 一个公共的 List 属性是奇怪的,见:Guidelines for Collections
-
您没有正确分配
getCustomerList作为CustomerItemList的getter,这意味着CustomerItemList永远不会被初始化并且会返回null。
标签: c# list constructor