首页 > 解决方案 > 是否有一种速记方法来检查空值以避免空引用异常?

问题描述

我有这段代码,它首先检查一个对象是否为空,如下所示:this.ButtonLabel.Text != null

    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if (this.ButtonLabel.Text != null && 
               (string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }

有没有一种方法可以清除对 null 的检查,然后在使用 if 块并进行初始this.ButtonLabel.Text检查之后从函数中返回?

标签: c#

解决方案


我认为这是您正在寻找的更清洁的代码:

private async void ChangeTheColours(Object sender, EventArgs e)
{
    if(string.IsNullOrWhiteSpace(this.ButtonLabel.Text))
         return;

    try
    {
        ConfigureColors((Button)sender, "C");
        await Task.Delay(200);
        ConfigureColors((Button)sender, State);
    }
    catch (Exception ex)
    {
        Crashes.TrackError(ex,
            new Dictionary<string, string> {
                    {"ChangeTheColours", "Exception"},
                    {"Device Model", DeviceInfo.Model },
            });
    }
}

如果您只需要检查null(而不是空格)并且您正在使用该对象,则可以使用安全导航运算符

代替

if(article != null && article.Author != null 
     && !string.IsNullOrWhiteSpace(article.Author.Name)){ }

写:

if(!string.IsNullOrWhiteSpace(article?.Author?.Name)){  }

推荐阅读