2

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

考虑以下带有 TimeSpan 的代码,它是一个结构:

// will not compile - illegal
TimeSpan ts = null;  

但是,以下代码确实可以编译并且是合法的,尽管表达式始终为假:

if (ts == null)
    Console.WriteLine("this line will never be hit");

有人能告诉我为什么将结构设置为 NULL 是无效的,但是可以将它与一个结构进行比较?

4

2 回答 2

7

它仍然是合法的,因为您可以重载 s 的==运算符struct

struct AmNull {
    public static bool operator ==(AmNull a, object b) {
        return b == null;
    }

    public static bool operator !=(AmNull a, object b) {
        return b != null;
    }
}

...

Console.WriteLine(new AmNull() == null); // True
于 2012-04-09T23:43:31.637 回答
3

无法为我编译:

struct Foo { }

class Program
{       
    static void Main( string[] args )
    {
        var f = new Foo();
        if( f == null ) { }
    }
}

错误 1 ​​运算符“==”不能应用于“ConsoleApplication3.Foo”和“null”类型的操作数

于 2012-04-09T23:42:22.700 回答