【发布时间】: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#