简体   繁体   English

为什么C#编译器会产生NULL和数字比较的结果?

[英]Why C# compiler yield result for NULL and number comparison?

I have the below code snippet which made TaskA to run when the Employee object is NULL (expected that to run TaskA only when the Employee ID not equals to 1). 我有以下代码片段,使Employee对象为NULL时运行TaskA(预期仅当Employee ID不等于1时运行TaskA)。

if (Employee?.Id != 1) <PerformTaskA>;

Here, why C# compiler compares NULL and 1? 在这里,为什么C#编译器比较NULL和1? shouldn't it throw exception? 它不应该抛出异常吗? Also, what is the better practice to avoid these kind of cases? 另外,避免此类情况的更好的做法是什么?

Why C# compiler compares NULL and 1? 为什么C#编译器比较NULL和1?

Because Nullable<T> is capable of comparing with T (or actually int becomes int? in this case). 因为Nullable<T>能够与比较T (或实际上int变得int?在这种情况下)。 And in your case, it ends up with null != 1 which is always true. 在您的情况下,它以null != 1结尾,这始终是正确的。

The easiest thing for you is to make this explicit: 对您来说,最简单的事情就是使它明确:

if (Employee != null && Employee.Id != 1) <PerformTaskA>;

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal) . 当您对nullable类型执行比较时,如果其中一个可为空的类型的值是null而另一个不是,则所有比较的结果均为false除了!= (not equal) It is important not to assume that because a particular comparison returns false, the opposite case returns true. 重要的不要假设因为特定的比较返回false,相反的情况返回true。 In the following example, 10 is not greater than, less than, nor equal to null. 在下面的示例中,10不大于,小于或等于null。 Only num1 != num2 evaluates to true. 只有num1!= num2计算为true。

int? num1 = 10;
int? num2 = null;
if (num1 >= num2)
{
    Console.WriteLine("num1 is greater than or equal to num2");
}
else
{
    // This clause is selected, but num1 is not less than num2.
    Console.WriteLine("num1 >= num2 returned false (but num1 < num2 also is false)");
}

if (num1 < num2)
{
    Console.WriteLine("num1 is less than num2");
}
else
{
    // The else clause is selected again, but num1 is not greater than
    // or equal to num2.
    Console.WriteLine("num1 < num2 returned false (but num1 >= num2 also is false)");
}

if (num1 != num2)
{
    // This comparison is true, num1 and num2 are not equal.
    Console.WriteLine("Finally, num1 != num2 returns true!");
}

// Change the value of num1, so that both num1 and num2 are null.
num1 = null;
if (num1 == num2)
{
    // The equality comparison returns true when both operands are null.
    Console.WriteLine("num1 == num2 returns true when the value of each is null");
}

/* Output: / *输出:

  • num1 >= num2 returned false (but num1 < num2 also is false) num1> = num2返回false(但是num1 <num2也为false)

  • num1 < num2 returned false (but num1 >= num2 also is false) num1 <num2返回假(但num1> = num2也为假)

  • Finally, num1 != num2 returns true! 最后,num1!= num2返回true!

  • num1 == num2 returns true when the value of each is null num1 == num2当每个值都为null时返回true

*/ * /

Check this Microsoft doc . 检查此Microsoft 文档

Check the Live Fiddle here . 这里查看Live Fiddle

You state "I have the below code snippet which made TaskA to run when the Employee object is NULL ". 您声明“我有以下代码段,当Employee对象为NULL时,TaskA可以运行”。

For that, you'd want: 为此,您需要:

if (employee == null) {
    PerformTaskA();
}

(NB: I've put employee rather than Employee on the assumption that employee refers to an object rather than its class / to be in line with naming standards ). (注:我以employee而不是Employee为前提,即employee是指对象而不是其类/以符合命名标准 )。

Were you just comparing with 1 because ID 1 means the employee is not null? 您是否只是在与1进行比较,因为ID 1表示员工不是null? That would also cause your task to run if the employee was not null but had any ID other than one; 如果雇员不为空,但具有除一个以外的其他ID,这也将导致您的任务运行。 though I suspect you realised that? 虽然我怀疑你意识到了吗?

Regarding comparison with a nullable type, see the documentation on Nullable.Equals , which explains this behaviour. 关于与可空类型的比较,请参阅有关Nullable.Equals的文档,该文档解释了此行为。

Employee?.Id evaluates to null if Employee is null. Employee?.Id的计算结果为null ,如果员工为null。
?. and ?[] null-conditional Operators 和?[]空条件运算符

Hover over this in Visual studio and you will get the answer 将鼠标悬停在Visual Studio中,您将获得答案

Debug.WriteLine(null != 1);

The expression will always be true because a value of type int will never equal null of type int? 该表达式将始终为true,因为int类型的值永远不会等于int类型的null?

It does not throw an exception. 它不会引发异常。 Why did you not test this? 你为什么不测试呢?

use 采用

Debug.WriteLine(sc != null && sc.ID != 1);

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

相关问题 为什么 C# 编译器将这个 != 比较转换为 &gt; 比较? - Why does the C# compiler translate this != comparison as if it were a > comparison? 为什么C#编译器不会抛出null的逻辑比较? - Why doesn't the C# compiler throw for logical comparisons of null? 为什么 C# 编译器无法检测到这不可能是 null? - Why can't the C# compiler detect that this can't be null? 为什么 C# 编译器认为这个空包引用可以为空? - Why does C# compiler thinks this nullbale reference can be null? 为什么 Python 的 UUID 构造函数与 C# Guid 构造函数产生不同的结果? - Why does Pythons UUID constructor yield a different result to the C# Guid constructor? C# 编译器无法将产量返回方法识别为类似? - C# compiler not recognizing yield return methods as similar? C#编译器编号文字 - C# compiler number literals Null 或 C# 中通用参数的默认比较 - Null or default comparison of generic argument in C# 数据集与空值C#的比较 - Dataset comparison with Null Value c# 为什么GETDATE()在SSMS和C#Microsoft.Practices.EnterpriseLibrary.Data上运行时会产生不同的结果? - Why do GETDATE() yield different result when run on SSMS vs. C# Microsoft.Practices.EnterpriseLibrary.Data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM