Possible Duplicate:
C# okay with comparing value types to null
考虑以下带有 TimeSpan 的代码,它是一个结构体:
// will not compile - illegal
TimeSpan ts = null;
但是,以下代码确实可以编译并且是合法的,尽管表达式总是错误的:
if (ts == null)
Console.WriteLine("this line will never be hit");
谁能告诉我为什么将结构设置为 NULL 是无效的,但可以将它与一个进行比较?
最佳答案
这仍然是合法的,因为您可以为 struct
s 重载 ==
运算符。
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
关于c# - 为什么在 C# 中将结构与 NULL 进行比较是合法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081231/