简体   繁体   English

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

[英]Why does the null-conditional operator behave differently for == and .Equals()?

I had the following code, which works fine: 我有以下代码,工作正常:

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

I wanted to make the string comparison case-insensitive, so I changed it to: 我想使字符串比较不区分大小写,所以我将其更改为:

var firstChild = token.First as JProperty;

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

Now the compiler is giving me an error: 现在编译器给了我一个错误:

Operator && cannot be applied to operands of type 'bool' and 'bool?' 运算符&&不能应用于'bool'和'bool?'类型的操作数

I can fix the error by coalescing to false like 我可以通过合并到false来修复错误

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

But I'm curious why the compiler doesn't like the first null-conditional syntax. 但我很好奇为什么编译器不喜欢第一个空条件语法。

Let's simplify to the essentials. 让我们简化一下要领。

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;

Basically .Equals() requires a non-null object to operate on. 基本上.Equals()需要一个非null对象来操作。 That's different than == , which is statically bound, not dynamically dispatched. 这与==不同,后者是静态绑定的,不是动态调度的。

the first expression returns null or bool 第一个表达式返回null或bool

if firstChild is null then the return value will be null and it can not be used in an if condition 如果firstChild为null,则返回值将为null,并且不能在if条件中使用

firstChild?.Name.Equals("href", StringComparison.OrdinalIgnoreCase)

will the same as 会像

firstChild == null ? null : firstChild.Name.Equals("href", StringComparison.OrdinalIgnoreCase)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM