比较“int”和“null”编译

本文关键字:编译 null 比较 int | 更新日期: 2023-09-27 17:55:27

可能的重复项:
C# 可以将值类型与空值进行比较

遇到了一个交叉,我刚才在 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值和一个常量null值(没有特定的类型)。 两个值之间唯一兼容的类型是int?,因此它们被强制int?并作为int? == int?进行比较。 某些int值作为int?肯定是非空的,null肯定是空的。 编译器意识到这一点,并且由于非空值不等于确定的null值,因此发出警告。

实际上编译

允许将"int?"与"int"进行比较,而不是将"int"与null进行比较,这是有意义的

例如

        int? nullableData = 5;
        int data = 10;
        data = (int)nullableData;// this make sense
        nullableData = data;// this make sense
        // you can assign null to int 
        nullableData = null;
        // same as above statment.
        nullableData = (int?)null;
        data = (int)(int?)null;
        // actually you are converting from 'int?' to 'int' 
        // which can be detected only at runtime if allowed or not

这就是你在int z = (int)(int?)null;中试图做的事情