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

c# – 为什么null条件运算符对==和.Equals()的行为不同?

发布时间:2020-12-15 23:26:53 所属栏目:百科 来源:网络整理
导读:我有以下代码,工作正常: var firstChild = token.First as JProperty;bool isHref = token.Children().Count() == 1 firstChild?.Name == "href"; 我想使字符串比较不区分大小写,所以我将其更改为: var firstChild = token.First as JProperty;bool isHref
我有以下代码,工作正常:

var firstChild = token.First as JProperty;
bool isHref = token.Children().Count() == 1
           && firstChild?.Name == "href";

我想使字符串比较不区分大小写,所以我将其更改为:

var firstChild = token.First as JProperty;

bool isHref = token.Children().Count() == 1
           && firstChild?.Name.Equals("href",StringComparison.OrdinalIgnoreCase);

现在编译器给了我一个错误:

Operator && cannot be applied to operands of type ‘bool’ and ‘bool?’

我可以通过合并到false来修复错误

bool isHref = token.Children().Count() == 1
         && (firstChild?.Name.Equals("href",StringComparison.OrdinalIgnoreCase) ?? false);

但我很好奇为什么编译器不喜欢第一个空条件语法.

解决方法

让我们简化一下要领.

string x = null,y = null;

// this is null.  b1 is bool?
var b1 = x?.Equals(y); 

// b2 is bool
// this is true,since the operator doesn't require non-null operands
var b2 = x == y;

基本上.Equals()需要一个非null对象来操作.这与==不同,后者是静态绑定的,不是动态调度的.

(编辑:李大同)

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

    推荐文章
      热点阅读