C# - 如何获得基础泛型的具体类型

bas*_*his 1 .net c# generics reflection

假设我有一个A类:

class A : B<C>, IA
{

}
Run Code Online (Sandbox Code Playgroud)

我也有这样的方法:

Type GetConcreteB<T>() where T : IA
{
//some code here...
}
Run Code Online (Sandbox Code Playgroud)

在这个方法中,我想检查是否T从任何继承B(当前我包装B到执行IB该操作的接口),如果是,则返回具体类型C.

所以,基本上我只想使用子类类型返回基类泛型类的具体类型.有没有办法实现这个目标?

Luc*_*ski 6

使用反射,遍历类层次结构,直到找到a 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;
}
Run Code Online (Sandbox Code Playgroud)