You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#构造函数警告:非可空属性CustomerItemList需非空的解决方法

解决C#非可空属性构造函数警告问题

这是C# 8.0+启用nullable引用类型检查后触发的警告:你声明了非可空的List<string>类型属性CustomerItemList,但默认构造函数没有为它赋值,编译器担心该属性可能在后续使用时为null。下面是几种实用的解决方式:


方法1:在构造函数中初始化属性

给Customer类添加构造函数,确保对象创建时CustomerItemList必有值:

class Customer : Inventory
{
    public List<string> CustomerItemList { get; set;}

    // 无参构造函数直接初始化空列表
    public Customer()
    {
        CustomerItemList = new List<string>();
    }

    // 可选:提供带参数的构造函数,强制外部传入合法值
    public Customer(List<string> customerItemList)
    {
        CustomerItemList = customerItemList ?? throw new ArgumentNullException(nameof(customerItemList));
    }

    // 你的getCustomerList方法...
}

方法2:属性声明时直接初始化

在属性定义时赋予默认值,无论用哪种方式创建对象,属性都不会为null:

class Customer : Inventory
{
    // 声明时初始化空列表
    public List<string> CustomerItemList { get; set;} = new List<string>();

    // 你的getCustomerList方法...
}

如果不需要外部修改该属性,还可以把set改为init(C# 9.0+支持),限制仅在对象初始化时赋值:

public List<string> CustomerItemList { get; init;} = new List<string>();

方法3:将属性声明为可空类型

如果业务逻辑允许CustomerItemList为null,给类型添加?标记为可空:

class Customer : Inventory
{
    public List<string>? CustomerItemList { get; set;}

    // 你的getCustomerList方法...
}

补充说明:你的getCustomerList方法里用对象初始化器给CustomerItemList赋值了,但编译器会检查所有创建Customer实例的场景(比如直接调用new Customer()),所以必须确保非可空属性在任何创建方式下都有值。

内容的提问来源于stack exchange,提问作者Kokila B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:05:22