为什么> =返回false时== null值返回true? [英] Why does >= return false when == returns true for null values?

查看:560
本文介绍了为什么> =返回false时== null值返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个int类型的变量? (或可空< INT>如果你愿意)。我想要做的两个变量大于或 - 等于(> =)比较,但事实证明,这种返回false如果两个变量是空的,而显然==操作符返回true。

I have two variables of type int? (or Nullable<int> if you will). I wanted to do a greater-than-or-equal (>=) comparison on the two variables but as it turns out, this returns false if both variables are null, while obviously the == operator returns true.

有人能向我解释为什么这是合乎逻辑的,因为> =运算符的语义定义包含或字?

Can someone explain to me why that is logical because the semantical definition of the >= operator contains the word "or"?

推荐答案

有大约在这个怪胎一个巨大的辩论时,该功能最初设计早在C 2.0#。问题是,C#用户完全习惯了这种被有意义的:

There was a huge debate about this oddity when the feature was originally designed back in C# 2.0. The problem is that C# users are completely used to this being meaningful:

if(someReference == null)

在延长平等空值类型,您有以下选择。

When extending equality to nullable value types, you have the following choices.

1),可为空值的平等是真正的取消的。如果操作数的一方或双方为null,则其结果既不是事实,也不是假的,但空。在这种情况下,您可以:

1) Nullable equality is truly lifted. If one or both of the operands is null then the result is neither true, nor false, but null. In this case you can either:

1A)是非法的,在一个如果的语句可空类型相等,因为如果语句需要一个布尔值,而不是一个可空布尔。相反,需要大家使用的HasValue如果他们想比较空。这是冗长和刺激性。

1a) Make it illegal to have a nullable value type equality in an "if" statement, because the "if" statement needs a bool, not a nullable bool. Instead, require everyone to use "HasValue" if they want to compare to null. This is verbose and irritating.

1b)中自动转换为null为false。这种方法的缺点是,如果x为空×== NULL返回false,这是混乱和对工作人员的空比较了解引用类型。

1b) Automatically convert null to false. The downside of this is that "x==null" returns false if x is null, which is confusing and works against people's understanding of null comparisons with reference types.

2)可空平等不举。可空平等是真或假,和比较为null是一个空检查。这使得可空不平等为空的平等不一致。

2) Nullable equality is not lifted. Nullable equality is either true or false, and comparison to null is a null check. This makes nullable equality inconsistent with nullable inequality.

这些选择都不是显然是正确的;它们都各有利弊。的VBScript选择1b中,例如。经过激烈的辩论在C#设计团队选择了#2。

None of these choices is obviously correct; they all have pros and cons. VBScript chooses 1b, for example. After much debate the C# design team chose #2.

这篇关于为什么&GT; =返回false时== null值返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆