为什么在C#中将结构与NULL合法进行比较?

时间:2012-04-09 23:38:39

标签: c# struct null

  

可能重复:
  C# okay with comparing value types to null

使用TimeSpan考虑以下代码,TimeSpan是一个结构:

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

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

无法为我编译:

struct Foo { }

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

错误1运算符'=='无法应用于'ConsoleApplication3.Foo'和'null'类型的操作数

相关问题