[英]Get different results for the same expression in C#
I am getting different results when changing from != true
to == false
which I thought is exactly the same.从!= true
更改为== false
时,我得到了不同的结果,我认为这完全一样。
This is my code这是我的代码
User user = await GetUser(id);
if (user == null || user.Orders?.Any() != true)
{
...
}
If I change to user.Orders?.Any() == true
some of my tests return different data.如果我更改为user.Orders?.Any() == true
我的一些测试会返回不同的数据。 Why?为什么?
Because user.Orders?.Any()
have bool?
因为user.Orders?.Any()
有bool?
type, because of '?'类型,因为 '?' after Orders.订单后。 So if user.Orders
is null
, then result of user.Orders?.Any()
will be null
and == true
will be false, while != false
will be true因此,如果user.Orders
为null
,则user.Orders?.Any()
的结果将为null
并且== true
将为 false,而!= false
将为 true
Your expression is a nullable boolean expression (bool?) which means that it has 3 results: true, false, null.您的表达式是一个可为空的 boolean 表达式(布尔?),这意味着它有 3 个结果:真、假、null。
That's why it is not the same != true
or == false
.这就是为什么它不一样!= true
或== false
。
In your case, if the user exists and his orders are null => the expression will return "null" result.在您的情况下,如果用户存在并且他的订单是 null => 表达式将返回“null”结果。 So that in case of != true
it will return true and in case of == false
it will return false because null != true != false
.因此,在!= true
的情况下,它将返回 true ,在== false
的情况下,它将返回 false ,因为null != true != false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.