C# okay with comparing value types to null(C# 可以将值类型与 null 进行比较)
问题描述
我今天遇到了这个问题,不知道为什么 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 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 可以将值类型与 null 进行比较


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01