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 进行比较
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
