1
/// <summary> /// Type 拓展 /// </summary> public static class TypeExtensions { /// <summary> /// 确定当前实例是否是继承或者实现某个Type /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsInheritOfType(this Type self, Type type) { if (type.IsInterface) return self.GetInterface(type.Name) != null; if (type.IsEnum) return self.GetEnumUnderlyingType() == type; return self.IsSubclassOf(type); //return type.IsAssignableFrom(self); } }
public static class TypeExtension { /// <summary> /// 支持判断祖先基类以及泛型基类 /// </summary> /// <param name="type"></param> /// <param name="baseType"></param> /// <returns></returns> public static bool IsSubclassOfEx(this Type type, Type baseType) { Type current = null; while (type != null && type != typeof(object)) { current = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (baseType == current) { return true; } type = type.BaseType; } return false; } }
测试:
public class Person { } public class Person<T> : Person { } public class Man : Person<int> { } public static void Main(string[] args) { bool a1 = typeof(Man).IsSubclassOf(typeof(Person));//true bool a2 = typeof(Man).IsSubclassOf(typeof(Person<>));//false bool a4 = typeof(Man).IsSubclassOf(typeof(Man));//false bool b1 = typeof(Man).IsSubclassOfEx(typeof(Person));//true bool b2 = typeof(Man).IsSubclassOfEx(typeof(Person<>));//true bool b4 = typeof(Man).IsSubclassOfEx(typeof(Man));//true }