如何用更简洁方式(如null条件/空合并运算符)编写C#条件表达式?
简化C#多层null判断的条件逻辑
你原来的多层null判断完全可以用null条件运算符(?.)简化,之所以用的时候出问题,是因为someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah")返回的是bool?(可空布尔类型)——中间任何一步为null时,整个表达式会返回null,直接强制转(bool)会在null时抛出异常。
下面是两种和原逻辑完全等价的简化写法:
方式1:结合空合并运算符(??)
把链式调用返回的null转为false,这样所有不满足条件的情况(包括null或不包含"Blah")都会进入else分支:
if (someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah") ?? false) { Console.WriteLine("found Blah"); } else { Console.WriteLine("Blah not found"); }
方式2:直接判断可空布尔值是否为true
可空布尔值只有明确为true时才满足条件,null或false都会进入else分支,逻辑和原代码一致:
if (someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah") == true) { Console.WriteLine("found Blah"); } else { Console.WriteLine("Blah not found"); }
完整示例代码
internal class SomeClass { public SomeChildClass ChildClassProperty { get; set; } } internal class SomeChildClass { public string SomeStringProperty { get; set; } } internal class Program { static void Main(string[] args) { SomeClass someClassVariable = new SomeClass(); // 方式1 if (someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah") ?? false) { Console.WriteLine("found Blah"); } else { Console.WriteLine("Blah not found"); } // 方式2 if (someClassVariable.ChildClassProperty?.SomeStringProperty?.Contains("Blah") == true) { Console.WriteLine("found Blah"); } else { Console.WriteLine("Blah not found"); } } }
内容的提问来源于stack exchange,提问作者InquisitiveLad
相关产品推荐
相关产品推荐

