泛型的继承判断:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interfaceTypes = givenType.GetInterfaces(); foreach (var it in interfaceTypes) { if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType) return true; } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) return true; Type baseType = givenType.BaseType; if (baseType == null) return false; return IsAssignableToGenericType(baseType, genericType); } |
比如泛型类声明:
1 |
abstract public class BaseClass<T> where T : BaseClass<T> |
子类 ClassA 声明
1 |
public class SubClass : BaseClass<SubClass> |
判断ClassA是否是BaseClass的子类:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Type tp = typeof(BaseClass<>); //Type baseType = SubClass.GetType().BaseType; Type baseType = typeof(SubClass); if (IsAssignableToGenericType(baseType, tp)) { //是继承关系 } else { //无继承关系 } |
取所有继承的子类(Type):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
static public List<Type> GetAllSubclasses(Type classType) //where T : class { var result = Assembly.GetExecutingAssembly() .GetTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == classType); List<Type> classes = new List<Type>(); foreach(var r in result) { classes.Add(r); } return classes; } |
比如带2个参数的泛型类 Class<T,U>,取继承于它的所有的子类的Type
1 |
GetAllSubclasses(typeof(Class<,>)); |