【发布时间】: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