【问题标题】:Is there a shorthand way to check for a null to avoid a null reference exception?是否有一种速记方法来检查空值以避免空引用异常?
【发布时间】:2019-05-28 15:33:57
【问题描述】:

我有这段代码首先检查对象是否为空,如下所示: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 检查之后从函数中返回?

【问题讨论】:

  • string.IsNullOrWhiteSpace
  • Substring 返回一个 string 所以没有理由强制转换。
  • @Ry- 即使是(不是),这也不是您在生产代码中想要的那种条件
  • @Ry- 什么工作是模式数学is: if(ButtonLabel.Text?[0] is char x && x!=' '){...}`跨度>
  • @Ry- 确实如此。但是,空检查没有真正意义。这是一个 XY 问题。我怀疑真正的问题是:How can I check whether a string isn't initialized?,在这种情况下答案是String.IsNullOrWhitespace。如果 OP 真的想匹配只有第一个字符是空格的非空字符串,IsNullOrEmpty 和字符检查。剩下的就是语言测验

标签: c#


【解决方案1】:

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

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(而不是空格)并且您正在使用该对象,则可以使用Safe navigation operator

而不是

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

写:

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

【讨论】:

  • 我想你忘记了!
  • 你能说在哪里!不见了?
  • @Alan2 我认为最后两个代码块显示了关于 string.IsNullOrWhiteSpace 调用的相反逻辑。
  • @Mahmoodvcs - 对于这个例子,使用 if(string.IsNullOrWhiteSpace(this?.ButtonLabel?.Text)) 会更安全吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2014-04-14
  • 1970-01-01
相关资源
最近更新 更多