问题描述
我今天遇到了这个问题,不知道为什么 C# 编译器没有抛出错误.
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?");
}
我很困惑 x 怎么可能为空.特别是因为这个赋值肯定会引发编译器错误:
I'm confused as to how x could ever possibly be null. Especially since this assignment definitely throws a compiler error:
Int32 x = null;
x 是否有可能变为空值,是微软决定不把这个检查放入编译器,还是完全错过了?
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?");
}
}
}
推荐答案
这是合法的,因为运算符重载解析有唯一的最佳运算符可供选择.有一个 == 运算符,它接受两个可为空的整数.int local 可转换为可为空的 int.null 文字可转换为可为 null 的 int.因此,这是 == 运算符的合法用法,并且总是会导致错误.
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.
同样,我们也允许你说if (x == 12.6)",这也总是假的.int local 可转换为 double,文字可转换为 double,显然它们永远不会相等.
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 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!