繁体   English   中英

如何通过反射获取泛型参数的类型

[英]How to get the type of a generic parameter by reflection

我需要通过反射获得泛型参数的泛型类型。 但真正的类型,而不是类型{Name =“T”; FullName = 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());

在其他therm中,我想知道如何调用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

我不知道这一切的重点,但是怎么样

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);
}

然后你有了运行时类型(如果有一个对象),否则你就有了静态类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM