如何比较操作适用于空中断? [英] How does comparison operator works with null int?

查看:132
本文介绍了如何比较操作适用于空中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习可空类型,跑进以下行为。

I am starting to learn nullable types and ran into following behavior.

虽然试图为空的INT,我看到比较运营商给了我意想不到的结果。例如,在我的下面code,输出我得到的是的既和1相等。注意,它不打印空为好。

While trying nullable int, i see comparison operator gives me unexpected result. For example, In my code below, The output i get is "both and 1 are equal". Note, it does not print "null" as well.

        int? a = null;
        int? b = 1;

        if (a < b)
            Console.WriteLine("{0} is bigger than {1}", b, a);
        else if (a > b)
            Console.WriteLine("{0} is bigger than {1}", a, b);
        else
            Console.WriteLine("both {0} and {1} are equal", a, b);

我希望任何非负整数会比空时,我失去了一些东西在这里?

I was hoping any non-negative integer would be greater than null, Am i missing something here ?

感谢

推荐答案

根据 MSDN - 这是在页面的运营商部分:

According to MSDN - it's down the page in the "Operators" section:

当你使用可空类型执行比较,如果可空类型之一的值是零,而另一个则不然,所有比较评估为假,除了!=

"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 !="

因此​​,无论 A&GT; b A&LT; b 评估为,因为 A 为空...

So both a > b and a < b evaluate to false since a is null...

这篇关于如何比较操作适用于空中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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