繁体   English   中英

泛型类型的反射子类

[英]Reflection subclass of generic type

在以下场景中:

public class A<T> { }

public class B : A<AClass> { }

是否可以在不指定 AClass (泛型参数)的情况下确定 B 是否是 A 的子类? 如:

typeof(B).IsSubclassOf(A<>)

是的,但您必须自己通过层次结构:

var instance = new B();
Type t = instance.GetType();

bool isA = false;
while(t != typeof(object))
{
    if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(A<>))
    {
        isA = true;
        break;
    }
    else
    {
        t = t.BaseType;
    }
}

@Lee的答案非常适合在整个基础 class层次结构中进行搜索。

如果有人需要确定子类是否继承自单个通用子类A<T>

Type t = typeof(B);
bool isSubClass = t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefination() == typeof(A<>);

可以使用扩展方法:

public static bool IsSubClassOfEx(Type t, Type baseType)
{
  return t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == baseType;
}

找到了一个简单的方法来做到这一点: if (B.GetType().BaseType.Name == typeof(A<>).Name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM