如何获取基类的泛型类型参数? [英] How to get base class's generic type parameter?

查看:96
本文介绍了如何获取基类的泛型类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个类,如下所示:

  public class TestEntity {} 

public class BaseClass< ; TEntity> {}

public class DerivedClass:BaseClass< TestEntity> {}

我已经得到 System.Type DerivedClass 的对象,在运行时使用反射。如何使用反射获取 TestEntity System.Type 对象?

谢谢。

解决方案

我假设你的代码只是一个样本,而你并没有明确知道 DerivedClass

  var type = GetSomeType(); 
var innerType = type.BaseType.GetGenericArguments()[0];

请注意,这段代码在运行时很容易失败,您应该验证您处理的类型是否是您期望它是:

  if(type.BaseType.IsGenericType 
&&& type.BaseType.GetGenericTypeDefinition )== typeof(BaseClass<>))

也可以有更深的继承树,以上条件将是必需的。


I have three class as following:

public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

I already get the System.Type object of DerivedClass using reflection in runtime. How can I get the System.Type object of TestEntity using reflection?

Thanks.

解决方案

I assume that your code is just a sample and you don't explicitly know DerivedClass.

var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];

Note that this code can fail very easily at run time you should verify if type you handle is what you expect it to be:

if(type.BaseType.IsGenericType 
     && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))

Also there can be deeper inheritance tree so some loop with above condition would be required.

这篇关于如何获取基类的泛型类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆