我注意到一些.NET结构可以与null相比较。例如:
TimeSpan y = new TimeSpan();
if (y == null)
return;
将编译得很好( Guid结构也是如此)。
现在我知道结构是值类型,上面的代码不应该编译,除非有一个重载的运算符==,它接受一个对象。但是,据我所知,并没有。
我用Reflector看过这个类,也看过MSDN上的文档。
这两个接口实现了以下接口:
IComparable, IComparable<T>, IEquatable<T>
但是,尝试实现相同的接口似乎没有帮助:
struct XX : IComparable, IComparable<XX>, IEquatable<XX> {
public int CompareTo(Object obj) {
return 0;
}
public int CompareTo (XX other){
return 0;
}
public bool Equals (XX other){
return false;
}
public override bool Equals(object value){
return false;
}
public static int Compare(XX t1, XX t2){
return 0;
}
}
我使用的是:.NET 2.0 Visual Studio2005。
有人知道这是什么原因吗?我只是想得到一个更好的理解。这不是问题,因为我知道无论如何我都不应该将structs与null进行比较。
发布于 2009-08-04 06:56:38
当包含可以为空的类型时,这个问题就被有效地引入。存在从TimeSpan
到TimeSpan?
的隐式转换,并且TimeSpan?
和该类型的空值之间存在比较。
编译器会对某些类型发出警告,这会让它更清楚自己想要做什么:
int x = 10;
if (x == null)
{
Console.WriteLine();
}
给出此警告:
Test.cs(9,13): warning CS0472: The result of the expression is always 'false'
since a value of type 'int' is never equal to 'null' of type 'int?'
我相信Marc Gravell和我解决了在什么情况下发出警告一次……遗憾的是,它并不一致。
发布于 2009-08-04 07:05:24
另请参阅:C# 3 (.NET 3.5) version of csc fails to report CS0162 for unrechable code (struct/null)
从C# 3编译器开始,这意味着它有时甚至不会对此发出警告;-p
因为Guid
/ TimeSpan
等提供了==
,所以它们落入了这个陷阱,因为它不会警告你。
https://stackoverflow.com/questions/1225949
复制相似问题