C# 可以将值类型与 null 进行比较
- 作者: flies
- 来源: 51数据库
- 2022-10-20
问题描述
我今天遇到了这个问题,不知道为什么 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
