如何在值为null时获取Nullable <int>的对象的类型</int>

时间:2012-08-15 20:02:42

标签: c# nullable

  

可能重复:
  .NET : How do you get the Type of a null object?

基本上我希望代码如下所示之一能够在没有空引用错误的情况下工作:

int? i1 = default(int?);
int? i2 = new Nullable<Int32>();
int? i3 = new int?();
var t1 = i1.GetType();
var t2 = i2.GetType();
var t3 = i3.GetType();

我希望/希望我能够从上面的 i 对象中获取类型,而不会出现空引用异常。

如果无法做到这一点,我怎样才能在保持空值的同时创建对Nullable Int的引用。

更新:对于那些感兴趣并且不想筛选链接问题中不完全适用的答案的人,解决方案是:

private void Example()
{
    var i = default(int?);
    var t = this.GetDeclaredType(i);
}

private Type GetDeclaredType<T>(T obj)
{
    return typeof(T);
}

0 个答案:

没有答案