【问题标题】:Warning in constructor in c# says its must contain a non-null value when exiting constructorc# 中构造函数中的警告说退出构造函数时它必须包含非空值
【发布时间】: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


【解决方案1】:

您没有在 Customer 对象中正确初始化 CustomerItemList。 您创建了一个客户列表,每个客户都有一个未初始化的名为 CustomerItemList 的列表。

您可以通过从您创建的现有列表进行初始化来添加它,如下所示:

  customers.Add(new Customer
        {
            CutomerId = "CUABC", CutomerName = "Bala", CustomerItemList = new List<string>(customerItemList1),
            InventoryQty = 25
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多