c#输出继承关系


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using UnityEditor;
using UnityEngine;

public class CheckScriptExtand
{

/// <summary>
/// log存储路径
/// </summary>
public static string savePath = "C:/ProgramData/ScriptsTool/Extand";

[MenuItem("Tools/查找所有继承自A的类(从第二层开始)", false, 1)]
static void Check()
{
//Thread myThread = new Thread(new ThreadStart(CheckScripts));
//myThread.Start();
CheckScripts();
}
static void CheckScripts()
{
Debug.LogError("开始检查,结果存入:" + savePath);
//继承关系包含A的脚本,C : B : A
List<string> res = GetSubClassNames(typeof(A),false);
//继承自B的脚本(上面一层)
List<string> resRemove1 = GetSubClassNames(typeof(B),true);
//继承自C的脚本(上面一层)
List<string> resRemove2 = GetSubClassNames(typeof(C),true);
List<string> showList = new List<string>();

for(int i=0;i<res.Count;i++)
{
if (!resRemove1.Contains(res[i]) && !resRemove2.Contains(res[i]))
showList.Add(res[i]);
}
WriteToTxt(showList);
Debug.LogError("完成");
}
/// <summary>
/// 获取一个类在其所在的程序集中的所有子类
/// </summary>
/// <param name="parentType">给定的类型</param>
/// <param name="oneLayer">只向上找一层</param>
/// <returns>所有子类的名称</returns>
public static List<string> GetSubClassNames(Type parentType,bool oneLayer)
{
var subTypeList = new List<Type>();
var assembly = parentType.Assembly;//获取当前父类所在的程序集``
var assemblyAllTypes = assembly.GetTypes();//获取该程序集中的所有类型
foreach (var itemType in assemblyAllTypes)//遍历所有类型进行查找
{
var baseType = itemType.BaseType;//逐层获取元素类型的基类,直到找到
if(baseType != null)
{
if(!oneLayer)
{
while (baseType.BaseType != null)
{
baseType = baseType.BaseType;
if (baseType.Name == parentType.Name)//如果基类就是给定的父类
{
subTypeList.Add(itemType);//加入子类表中
}
}
}
else
{
if (baseType.Name == parentType.Name)//如果基类就是给定的父类
{
subTypeList.Add(itemType);//加入子类表中
}
}

}

}
return subTypeList.Select(item => item.Name).ToList();//获取所有子类类型的名称
}
/// <summary>
/// 写入txt
/// </summary>
/// <param name="path"></param>
/// <param name="context"></param>
private static void WriteToTxt(List<string> context)
{
string path = savePath + "/" + "data.txt";
//生成目录
//创建文件夹
if (Directory.Exists(savePath) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(path);
}
if (!File.Exists(path))
{
FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件
StreamWriter sw = new StreamWriter(fs1, Encoding.UTF8);
for (int i = 0; i < context.Count; i++)
{
sw.WriteLine(context[i]);//开始写入值
}

sw.Close();
fs1.Close();
}
else
{
File.Delete(path);
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs, Encoding.UTF8);
for (int i = 0; i < context.Count; i++)
{
sr.WriteLine(context[i]);//开始写入值
}
fs.Flush();
sr.Close();
fs.Close();
}
}
}

posted @ 2022-07-25 11:44  mc宇少  阅读(52)  评论(0编辑  收藏  举报