英文:
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
,您需要将结果与 bool
值 true
进行比较。
您还可以使用传统的空检查:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论