代码之家  ›  专栏  ›  技术社区  ›  Tom Deloford

如何使用反射确定基类的泛型参数

  •  1
  • Tom Deloford  · 技术社区  · 17 年前

    我有以下结构

    public class MyClass : MyBaseClass<System.Int32>
    {
    }
    

    在静态方法中,如果不实例化新的MyClass实例,如何获取用于构建具体基类的泛型参数的类型?例如,在上面的示例system.int32中

    2 回复  |  直到 17 年前
        1
  •  5
  •   JaredPar    17 年前

    试试这个

    public static Type GetBaseTypeGenericArgument(Type type) {
      return type.BaseType.GetGenericArguments()[0];
    }
    
    ...
    GetBaseTypeGenericArgument(typeof(MyClass));
    
        2
  •  0
  •   Darin Dimitrov    17 年前
    Type arg = typeof(MyClass).BaseType.GetGenericArguments()[0];