如何解决空检查语句中的空引用异常?

How to resolve a null reference exception in a null check statement?

我已经向布尔方法添加了空 属性 检查,以防止在 SelectedCustomer 属性.

中的任何字符串字段为空时返回 true

问题是在我将任何数据输入 SelectedCustomer 模型之前,构造函数调用了我的 bool 方法。然后这会导致 Null 引用异常。

从我在语句上设置的断点可以看出,“{"Object reference not set to an instance of an object."}”是错误的。 selectedCustomer 属性 在我 select 来自数据网格的客户之前不会初始化。

我的问题是,如何在不导致 NRE 的情况下以这种方式执行 null 检查?

这是我执行空值检查的 CanModifyCustomer 布尔方法:

private bool CanModifyCustomer(object obj)
{

    if (SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null && SelectedCustomer != null)
    {
        return true;
    }

    return false;            
}

它在我的按钮命令中作为参数传递:

public MainViewModel(ICustomerDataService customerDataService) 
{
    this._customerDataService = customerDataService;
    QueryDataFromPersistence();

    UpdateCommand = new CustomCommand((c) => UpdateCustomerAsync(c).FireAndLogErrors(), CanModifyCustomer);

}

这是执行空值检查的 SelectedCustomer 属性:

 private CustomerModel selectedCustomer;
    public CustomerModel SelectedCustomer
    {
        get
        {
            return selectedCustomer;
        }
        set
        {
            selectedCustomer = value;
            RaisePropertyChanged("SelectedCustomer");
        }
    }

只需使用空条件运算符。 (C#6)

if (SelectedCustomer?.FirstName != null && SelectedCustomer.LastName != null)
{
    return true;
}

或者你应该把SelectedCustomer != null放在第一位。因为条件是从左到右评估的。因此,如果第一个因为使用 && 运算符而为假,它将不会继续检查其他部分并且条件变为假。

if (SelectedCustomer != null && SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null)
{
    return true;
}