【问题标题】:How to get the type of a generic parameter by reflection如何通过反射获取泛型参数的类型
【发布时间】:2012-09-08 03:45:03
【问题描述】:

我需要通过反射得到一个泛型参数的泛型类型。但真正的类型,而不是类型 { Name="T" ;全名=null }

public void Sample<T>(T i, object o)
{
    MethodBase basee = MethodBase.GetCurrentMethod();
    Type[] types = basee.GetGenericArguments();
}

但我不能使用 typeof(T),因为我正在使用反射

有没有办法(使用反射)获取泛型参数的类型。

// in this case i should get (Type) { Name="Int32" ; FullName="System.Int32" }
myClassObj.Sample(10, new object());

在其他方面,我想知道如何调用 typeof(T) ex 调用的方法:

// in Il code I see that the compiler use:
// ldtoken !!T => this should get the RuntimeTypeHandle needed as parameter
// System.Type::GetTypeFromHandle(valuetype System.RuntimeTypeHandle)
Type t = Type.GetTypeFromHandle( ? ? ? ); 

如何从 T 泛型参数中获取 RuntimTypeHandle

【问题讨论】:

  • 为什么不能使用i.GetType()?就此而言,为什么不能使用 typeof(T)?这会告诉你它是一个 int。
  • 我的值可能为空,并导致崩溃...:S
  • 很公平。但为什么不用 typeof(T)?

标签: c# reflection methodinfo generic-method


【解决方案1】:

我不知道这一切的意义,但是呢

public void Sample<T>(T i, object o)
{
  Type t = typeof(T);
  if (i != null)
  {
    t = i.GetType();
  }

  // Do whatever with t
  Console.WriteLine(t);
}

那么你就得到了运行时类型(如果有对象的话),否则你就得到了静态类型。

【讨论】:

  • +1(恭喜获得 2000 分),但我建议使用更简洁的表达方式:Type t = i == null ? typeof(T) : i.GetType();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多