加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:15:55 所属栏目:百科 来源:网络整理
导读:来自这个问题 why does n.GetHashCode() work but n.GetType() throws and exception? Jon给出的答案引导我提出这个问题:为什么不是Nullable隐藏GetType: public new Type GetType(){ return GetValueOrDefault().GetType();} 因为那么 int? i = null;Cons
来自这个问题 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的契约.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读