C# 反射:如何获取通用对象的类型

问题描述

假设我有以下课程

public class MyClass<T>
{
  public Method(T input)
  {
    //performs logic with input
  }
}

我想将 MyClass 类型存储在一个类似的值中

Type classtype = typeof(MyClass);

但由于 MyClass 是一个泛型类,如果不声明像 typeof(MyClass<AnotherClass>) 这样的泛型,我无法执行该操作。

有没有办法让这个工作?

我写过类似的东西

private void Performlogic(Type inputType)
{
      MethodInfo getTypeMethod = typeof(this).getmethod("GetType");
      getTypeMethod = getTypeMethod.MakeGenericmethod(inputType);
      Type result = (Type)getTypeMethod.Invoke(default,default);
      
      // ...
}

private static Type GetType<T>()
    where T : class
{
    Type type = typeof(MyClass<T>);
    return type;
}

但我觉得有一种更简洁的方法可以做到这一点,而无需创建带有“0 个引用”的额外方法

解决方法

在“用输入执行逻辑”处,你可以写:

  • typeof(T) 检查类型参数 T
  • 的类型信息
  • typeof(MyClass<>)MyClass<> 类型检查为泛型类型定义
  • typeof(MyClass<T>) 检查 MyClass<T> 的封闭泛型类型。