c# - 是否有一种速记方法来检查空值以避免空引用异常?
问题描述
我有这段代码,它首先检查一个对象是否为空,如下所示: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
检查之后从函数中返回?
解决方案
我认为这是您正在寻找的更清洁的代码:
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)){ }
推荐阅读
- python - 除数数?
- hive - Presto + 运行 presto 查询时打开 Hive 拆分时出错
- python - 如何让联合核密度图在黑色背景上看起来更好(seaborn)
- python - 根据列值的条件从主数据框创建新的数据框(不使用.ix)
- python - Tkinter:无法让网格几何管理器使用框架
- django - django modelmanager 查询集不返回页面
- c - Android NDK SIGSEGV 致命信号 11,代码 2 (SEGV_ACCERR)
- python - 使用 pandas 对象计算公式
- javascript - ReactJS在运行函数后清除textarea值
- python - Python中函数的奇怪热编码问题