微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – Nullable <>为什么不隐藏GetType?

来自这个问题 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的契约.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐