我有三个类如下:
public class TestEntity { } public class BaseClass<TEntity> { } public class DerivedClass : BaseClass<TestEntity> { }
我已经在运行时使用反射获取DerivedClass的System.Type对象.如何使用反射获取TestEntity的System.Type对象?
谢谢.
解决方法
@H_403_11@ 我假设你的代码只是一个示例,你不明确地知道DerivedClass.var type = GetSomeType(); var innerType = type.BaseType.GetGenericArguments()[0];
请注意,此代码在运行时可能会非常容易失败,您应该验证您处理的类型是您期望的类型:
if(type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))
也可以有更深的继承树,因此需要一些具有上述条件的循环.