如何获取基类的泛型类型参数?

luc*_*ucn 19 c# generics reflection

我有三个课程如下:

public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }
Run Code Online (Sandbox Code Playgroud)

我已经在运行时获得了使用反射的System.Type对象DerivedClass.如何获得使用反射的System.Type对象TestEntity

谢谢.

Raf*_*fal 30

我假设您的代码只是一个示例而您没有明确知道DerivedClass.

var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];
Run Code Online (Sandbox Code Playgroud)

请注意,此代码在运行时很容易失败,您应该验证您处理的类型是否符合您的预期:

if(type.BaseType.IsGenericType 
     && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))
Run Code Online (Sandbox Code Playgroud)

也可以有更深的继承树,因此需要一些具有上述条件的循环.


Eli*_*bel 5

您可以使用 BaseType 属性。以下代码对于继承中的更改具有弹性(例如,如果您在中间添加另一个类):

Type GetBaseType(Type type)
{
   while (type.BaseType != null)
   {
      type = type.BaseType;
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(BaseClass<>))
      {
          return type.GetGenericArguments()[0];
      }
   }
   throw new InvalidOperationException("Base type was not found");
}

// to use:
GetBaseType(typeof(DerivedClass))
Run Code Online (Sandbox Code Playgroud)