c# - 比较 'int' 和 'null' 编译

标签 c#

<分区>

Possible Duplicate:
C# okay with comparing value types to null

我刚刚在 C# (4.0) 编译器中发现了一些奇怪的东西。

int x = 0;
if (x == null) // Only gives a warning - 'expression is always false'
    x = 1;

int y = (int)null; // Compile error
int z = (int)(int?)null; // Compiles, but runtime error 'Nullable object must have a value.'

如果您不能将null 分配给int,为什么编译器允许您比较它们(它只给出警告)?

有趣的是,编译器不允许以下内容:

struct myStruct
{
};

myStruct s = new myStruct();
if (s == null) // does NOT compile
    ;

为什么 struct 示例无法编译,而 int 示例可以?

最佳答案

进行比较时,编译器会尽量使比较的两个操作数具有兼容的类型。

它有一个 int 值和一个常量 null 值(没有特定类型)。这两个值之间唯一兼容的类型是 int? 因此它们被强制转换为 int? 并与 int? == 整数?。某些 int 值作为 int? 肯定是非空的,而 null 肯定是空的。编译器意识到这一点,并且由于非空值不等于确定的 null 值,因此发出警告。

关于c# - 比较 'int' 和 'null' 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493540/

相关文章:

C# XNA 4.0 全屏鼠标移入第二个显示器

c# - MVC3 数据绑定(bind)

c# - System.Security.Principal.WindowsIdentity 和 WinForms 身份验证

c# - 如何在 Refit 中禁用 urlencoding get-params?

c# - 查找文件的更改

c# - asp.net 回传上的 https 警告

c# - 使用它的指针从托管 C# 中释放非托管内存

c# - System.Timers.Timer timer1_Elapsed 未触发!帮助!

c# - 将右侧 UITableViewCell 中的标签与自动布局对齐

c# - 如何在 Blazor 服务器中设置同意 cookie