Skip to main content
 首页 » 编程设计

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

2024年02月20日15xiaohuochai

我需要通过反射获取泛型参数的泛型类型。但真正的类型,而不是类型 { Name="T";全名=空 }

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

请您参考如下方法:

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

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

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