Lee*_*som 6 c# c#-6.0 null-conditional-operator
观察:如果text为null,则此方法返回True.我期待False.
return text?.IndexOf('A') != -1;
Run Code Online (Sandbox Code Playgroud)
当我使用ILSpy(或检查IL)反映上述行时,这是生成的代码:
return text == null || text.IndexOf('A') != -1;
Run Code Online (Sandbox Code Playgroud)
这是我真正需要满足我的期望:
return text != null && text.IndexOf('A') != -1;
Run Code Online (Sandbox Code Playgroud)
问题:有人对Null条件代码生成OR表达式的原因有一个很好的解释吗?
上面的行实际上涉及两个操作:空条件运算符方法调用和比较.如果将第一个运算符的结果存储为中间变量会发生什么?
int? intermediate = text?.IndexOf('A');
return intermediate != -1;
Run Code Online (Sandbox Code Playgroud)
显然,如果text为null,则intermediate也将为null.将其与任何整数值进行比较!=将返回true.
来自MSDN(强调我的):
当您使用可空类型进行比较时,如果其中一个可空类型的值为null而另一个不是,则除了!=(不等于)之外,所有比较都会计算为false .
此代码可以使用空条件运算符,只要你可以使用不同的运营商,以确保一个比较空的计算结果将被写入false.在这种情况下,
return text?.IndexOf('A') > -1;
Run Code Online (Sandbox Code Playgroud)
将返回您预期的输出.