简体   繁体   English

在 C# 中获得相同表达式的不同结果

[英]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.Ordersnull ,则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.

相关问题 为什么这个表达式在 C# 和 C++ 中产生不同的结果? - Why does this expression produce different results in C# and C++? 如何在 c# 中正确获取 csv 文件 header? 相同的代码得到不同的结果 - How to properly get csv file header in c#? Getting different results for same code 以相同的方式加密javascript和C#中的字符串以获得相同的结果 - Encrypt string in javascript and C# by the same way to get same results C# OpenGL - 相同的可执行文件有时会显示不同的结果 - C# OpenGL - Same Executable sometimes shows different results 相同的Excel公式在Visual Studio C#中返回不同的结果 - Same Excel formula returns different results in Visual Studio C# C#序列化-同一输入产生完全不同的结果? - c# serialization - same input producing completely different results? Powershell 从 c# 运行相同的脚本返回不同的结果 - Powershell return different results running the same script from c# c# Pinvoke with StringBuilder为相同的方法返回不同的结果 - c# Pinvoke with StringBuilder returns different results for the same method 为什么在C#中处理相同的异常时会有两个不同的结果? - Why two different results while handling the same Exception in C#? C#和VB.Net给出了相同方程的不同结果 - C# and VB.Net give different results for the same equation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM