C# - 如何获取基本泛型的具体类型
C# - How to get the concrete type of base generic
假设我有一个 class A:
class A : B<C>, IA
{
}
我也有这样的方法:
Type GetConcreteB<T>() where T : IA
{
//some code here...
}
在这个方法中,我想检查 T
是否继承自任何 B
(目前我将 B
包装到一个接口 IB
中,它可以做这件事)和如果是,return C
的具体类型。
所以,基本上我想 return 基本泛型的具体类型 class 只使用 subclass 类型。有办法实现吗?
使用反射,遍历 class 层次结构,直到找到 B<T>
,然后提取 T
:
static Type GetConcreteB<T>()
where T : IA
{
var t = typeof(T);
while (t != null) {
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(B<>))
return t.GetGenericArguments()[0];
t = t.BaseType;
}
return null;
}
假设我有一个 class A:
class A : B<C>, IA
{
}
我也有这样的方法:
Type GetConcreteB<T>() where T : IA
{
//some code here...
}
在这个方法中,我想检查 T
是否继承自任何 B
(目前我将 B
包装到一个接口 IB
中,它可以做这件事)和如果是,return C
的具体类型。
所以,基本上我想 return 基本泛型的具体类型 class 只使用 subclass 类型。有办法实现吗?
使用反射,遍历 class 层次结构,直到找到 B<T>
,然后提取 T
:
static Type GetConcreteB<T>()
where T : IA
{
var t = typeof(T);
while (t != null) {
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(B<>))
return t.GetGenericArguments()[0];
t = t.BaseType;
}
return null;
}