加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当text为null时,text?.IndexOf(ch)!= -1为True?

发布时间:2020-12-15 04:29:56 所属栏目:百科 来源:网络整理
导读:观察:如果text为null,则此方法返回True.我期待False. return text?.IndexOf('A') != -1; 当我使用ILSpy(或检查IL)反映上述行时,这是生成的代码: return text == null || text.IndexOf('A') != -1; 这是我真正需要满足我的期望: return text != null text.
观察:如果text为null,则此方法返回True.我期待False.
return text?.IndexOf('A') != -1;

当我使用ILSpy(或检查IL)反映上述行时,这是生成的代码:

return text == null || text.IndexOf('A') != -1;

这是我真正需要满足我的期望:

return text != null && text.IndexOf('A') != -1;

问题:有人对Null条件代码生成OR表达式的原因有一个很好的解释吗?

完整样品:https://dotnetfiddle.net/T1iI1c

解决方法

上面的行实际上涉及两个操作:空条件运算符方法调用和比较.如果将第一个运算符的结果存储为中间变量会发生什么?
int? intermediate = text?.IndexOf('A');
return intermediate != -1;

显然,如果text为null,则intermediate也将为null.使用!=将其与任何整数值进行比较将返回true.

From MSDN(强调我的):

When you perform comparisons with nullable types,if the value of one of the nullable types is null and the other is not,all comparisons evaluate to false except for != (not equal).

只要您可以使用不同的运算符来确保与null的比较计算结果为false,就可以使用空条件运算符编写此代码.在这种情况下,

return text?.IndexOf('A') > -1;

将返回您预期的输出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读