C#没关系与比较值类型为null [英] C# okay with comparing value types to null

查看:138
本文介绍了C#没关系与比较值类型为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个今天不知道为什么C#编译器不会引发错误。

 的Int32 X = 1;
如果(X == NULL)
{
    Console.WriteLine(什么?);
}

我很困惑,如何十大可能永远不可能为空。特别是因为这种分配绝对抛出一个编译器错误:

 的Int32 X = NULL;

是否有可能是X可能成为空,没有微软刚刚决定不把这个检查到编译器,或者是它完全错过了?

更新:与code搞乱写这篇文章后,突然编译器想出了一个警告,即前pression将永远是正确的。现在我真的失去了。我把对象变成一个类,现在警告已经走了,但留下的问题,可以在值类型最终被空。

 公共类测试
{
    公开日期时间A日期= DateTime.Now;    公开测试()
    {
        测试测试=新测试();
        如果(test.ADate == NULL)
        {
            Console.WriteLine(什么?);
        }
    }
}


解决方案

这是合法的,因为运算符重载决策必须选择一个独特的最好的运营商。有一个==操作符带有两个可空的整数。的int地方可以转换为可空int类型。 null文本可以转换为可空int类型。因此,这是==操作符的合法使用,而且将永远导致错误的。

同样,我们也允许你说:如果(X == 12.6),这也将永远是假的。的int地方可以转换为双,文字可以转换为双,显然他们将永远是平等的。

I ran into this today and have no idea why the C# compiler isn't throwing an error.

Int32 x = 1;
if (x == null)
{
    Console.WriteLine("What the?");
}

I'm confused as to how x could ever possibly be null. Especially since this assignment definitely throws a compiler error:

Int32 x = null;

Is it possible that x could become null, did Microsoft just decide to not put this check into the compiler, or was it missed completely?

Update: After messing with the code to write this article, suddenly the compiler came up with a warning that the expression would never be true. Now I'm really lost. I put the object into a class and now the warning has gone away but left with the question, can a value type end up being null.

public class Test
{
    public DateTime ADate = DateTime.Now;

    public Test ()
    {
        Test test = new Test();
        if (test.ADate == null)
        {
            Console.WriteLine("What the?");
        }
    }
}

解决方案

This is legal because operator overload resolution has a unique best operator to choose. There is an == operator that takes two nullable ints. The int local is convertible to a nullable int. The null literal is convertible to a nullable int. Therefore this is a legal usage of the == operator, and will always result in false.

Similarly, we also allow you to say "if (x == 12.6)", which will also always be false. The int local is convertible to a double, the literal is convertible to a double, and obviously they will never be equal.

这篇关于C#没关系与比较值类型为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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