我有这段代码会首先检查对象是否为空,例如: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 },
});
}
}
有没有一种方法可以清理空值检查,并且比使用if块并进行初始this.ButtonLabel.Text
检查还要晚些从函数返回?
答案 0 :(得分:4)
我认为这是您正在寻找的更干净的代码:
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)){ }