一下实例以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));
}