来自这个问题
why does n.GetHashCode() work but n.GetType() throws and exception? Jon给出的答案引导我提出这个问题:为什么不是Nullable<>隐藏GetType:
public new Type GetType() { return GetValueOrDefault().GetType(); }
因为那么
int? i = null; Console.WriteLine(i.GetType().Name);
应该工作,不应该吗?我错过了一些明显的东西吗有什么警告?我试过谷歌,但没有找到任何令人满意的解释.
更新:澄清:有点.这有效:
int? i = null; Console.WriteLine(i.GetHashCode());
i.GetType()抛出的唯一原因是因为GetType不是虚拟的并且无法被覆盖.因此,当调用它时,我被装入对象,导致null然后它抛出.但是如果Nullable会像这样实现的话
public struct Nullable<T> where T : struct { .... public new Type GetType() { return GetValueOrDefault().GetType(); } }
然后它会使行为更加一致(imho),所有这些都可以工作,而不仅仅是前两个调用:
int? i = null; Console.WriteLine(i.GetHashCode()); Console.WriteLine(i.ToString()); Console.WriteLine(i.GetType());
解决方法
我认为这是因为GetType返回当前实例的确切运行时类型.在这种情况下,它没有运行时类型,因为它引用了null.
考虑这个例子:
MyBaseClass myBase = null; MyDerivedClass myDerived = null; object o = myDerived; MyBaseClass b = myDerived;
如果myBase.GetType()将返回MyBaseClass而myDerived.GetType()将返回MyDerivedClass,那么o.GetType()和b.GetType()应返回什么?
Nullable不是简单地隐藏object.GetType并且当它为null时返回其编译时类型的原因,可能是因为它会破坏GetType的契约.