在一个程序集中获取一个类的所有子类

一下实例以Exception 为例 主要代码:

辅助类:

  class CustType
    {
        List<CustType> list;
        public CustType(Type currentType)
        {
            CurrentType = currentType;
            list = new List<CustType>();
        }
        public Type CurrentType { get; private set; }
        public CustType ParentType { get; set; }
        public List<CustType> SubType { get { return list; } }

        public static void AddTypeToCustType(CustType source, CustType target)
        {
            target = FindCustType(source, target);
            source.ParentType = target;
            target.SubType.Add(source);
            ChangeCustType(target);
        }
        public static CustType FindCustType(CustType source, CustType target)
        {
            foreach (CustType ty in target.SubType)
            {
                if (source.CurrentType.IsSubclassOf(ty.CurrentType))
                    return FindCustType(source, ty);
            }
            return target;
        }
        public static void ChangeCustType(CustType type)
        {
            for (int i = 0; i < type.SubType.Count-1; i++)
            {
                for (int j = i + 1; j < type.SubType.Count; j++)
                {
                    if (type.SubType[i].CurrentType.IsSubclassOf(type.SubType[j].CurrentType))
                    {
                        type.SubType[j].SubType.Add(type.SubType[i]);
                        type.SubType.Remove(type.SubType[i]);
                    }
                    else if (type.SubType[j].CurrentType.IsSubclassOf(type.SubType[i].CurrentType))
                    {
                        type.SubType[i].SubType.Add(type.SubType[j]);
                        type.SubType.Remove(type.SubType[j]);
                    }
                   
                }
            }
        }
    }

 

主函数

  CustType cuType;
        void GetList()
        {
            Type type = typeof(System.Exception);
            List<CustType> list = new List<CustType>();
            cuType = new CustType(type);
           
            Type[] types = Assembly.GetAssembly(type).GetTypes();
            foreach (Type ty in types)
                if (ty.IsClass && ty.IsSubclassOf(type))
                    list.Add(new CustType(ty));

            foreach (CustType ty in list)
            {
                CustType.AddTypeToCustType(ty, cuType);
            }
            //Test
            CustType temp = cuType.SubType[0].SubType.Find(x => x.CurrentType == typeof(ArgumentException));
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值