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

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

概述我有以下代码,工作正常: var firstChild = token.First as JProperty;bool isHref = token.Children().Count() == 1 && firstChild?.Name == "href"; 我想使字符串比较不区分大小写,所以我将其更改为: var firstChild = token.First as J 我有以下代码,工作正常:

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 operandsvar b2 = x == y;

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

总结

以上是内存溢出为你收集整理的c# – 为什么null条件运算符对==和.Equals()的行为不同?全部内容,希望文章能够帮你解决c# – 为什么null条件运算符对==和.Equals()的行为不同?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1219625.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存