• Type扩展类


    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
    
            }
  • 相关阅读:
    STL容器 erase的使用陷井
    转:VC++线程同步-事件对象
    VC线程同步方法
    C/C++四种退出线程的方法
    rabbitMQ 常用命令
    Spring @Configuration
    Spring RabbitMQ 延迟队列
    rabbitmq web管理界面 用户管理
    Linux下tar.gz 安装
    Linux下RPM软件包的安装及卸载
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/13569856.html
Copyright © 2020-2023  润新知