加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:36:32 所属栏目:百科 来源:网络整理
导读:我有三个类如下: public class TestEntity { }public class BaseClassTEntity { }public class DerivedClass : BaseClassTestEntity { } 我已经在运行时使用反射获取DerivedClass的System.Type对象.如何使用反射获取TestEntity的System.Type对象? 谢谢. 解
我有三个类如下:
public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

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

谢谢.

解决方法

我假设你的代码只是一个示例,你不明确地知道DerivedClass.
var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];

请注意,此代码在运行时可能会非常容易失败,您应该验证您处理的类型是您期望的类型:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读