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

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

辅助类:

  class CustType
    {
        List list;
        public CustType(Type currentType)
        {
            CurrentType = currentType;
            list = new List();
        }
        public Type CurrentType { get; private set; }
        public CustType ParentType { get; set; }
        public List 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 list = new List();
            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));
        }

你可能感兴趣的:(C#.NET基础)