zoukankan      html  css  js  c++  java
  • 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
    
            }
  • 相关阅读:
    H5本地存储
    小知识(h5 js )
    在ubuntu18.04版本安装vscode
    函数基本操作
    python直接赋值、深浅拷贝实例剖析
    collections模块简介
    set()集合基本操作
    list、tuple、dict内部功能释义
    str内部方法释义
    int内部方法释义
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/13569856.html
Copyright © 2011-2022 走看看