C# – 包含引发空异常

huangapple go评论51阅读模式
英文:

C# - contains throws null exception

问题

如果 SegroupOf 为 null,如何处理?我已将 SegroupOf 声明为可为空 (nullable),如何确保即使它为 null,也不会引发任何错误?

英文:

My code

 string? SegroupOf;

 if(SegroupOf.Contains("Team"))
 {
    
 }

If SegroupOf is null it throws an error. How to handle null? I have given SegroupOf as nullable, how to make sure even if its null it doesnot throw any error

答案1

得分: 5

你可以这样使用null-conditional-operator

if(SegroupOf?.Contains("Team") == true)

然而,由于 SegroupOf?.Contains 返回 bool? 而不是 bool,您需要将结果与 booltrue 进行比较。

您还可以使用传统的空检查:

if(Segroup != null && Segroup.Contains("Team"))

然而,这与空条件操作符略有不同,因为空条件操作符是短路的,意味着 Segroup 只被访问一次,而在第二种情况下被访问两次。

英文:

You can use the null-conditional-operator like so:

if(SegroupOf?.Contains("Team") == true)

However as SegroupOf?.Contains returns a bool? instead of bool, you need to compare the result to the bool-value true.

You can also just use old-school null-check:

if(Segroup != null && Segroup.Contains("Team"))

However that is slightly different as the null-conditional is short-circuiting, meaning Segroup is only accessed once, while in the second case it's accessed two times.

huangapple
  • 本文由 发表于 2023年6月27日 19:26:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定