106 lines
3.1 KiB
C#
106 lines
3.1 KiB
C#
|
|
||
|
using System.Reflection;
|
||
|
|
||
|
namespace Debug.MODS;
|
||
|
public class TypeHelper<TBase>
|
||
|
{
|
||
|
public readonly List<Type> result = [];
|
||
|
readonly string Title = "Title";
|
||
|
readonly string Priority = "Priority";
|
||
|
public TypeHelper()
|
||
|
{
|
||
|
Run();
|
||
|
}
|
||
|
public TypeHelper(string title, string Priority)
|
||
|
{
|
||
|
this.Title = title;
|
||
|
this.Priority = Priority;
|
||
|
Run();
|
||
|
}
|
||
|
|
||
|
private void Run()
|
||
|
{
|
||
|
GetTypesInheritingFrom();
|
||
|
}
|
||
|
|
||
|
public void showUI()
|
||
|
{
|
||
|
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// 获取所有继承自指定基类的类型
|
||
|
/// </summary>
|
||
|
/// <typeparam name="TBase">基类</typeparam>
|
||
|
/// <returns>继承自基类的类型列表</returns>
|
||
|
public List<Type> GetTypesInheritingFrom()
|
||
|
{
|
||
|
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
foreach (var type in assembly.GetTypes())
|
||
|
{
|
||
|
if (typeof(TBase).IsAssignableFrom(type) && type != typeof(TBase))
|
||
|
{
|
||
|
result.Add(type);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
catch (ReflectionTypeLoadException ex)
|
||
|
{
|
||
|
foreach (var type in ex.Types.Where(t => t != null))
|
||
|
{
|
||
|
if (typeof(TBase).IsAssignableFrom(type) && type != typeof(TBase))
|
||
|
{
|
||
|
result.Add(type);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
// GetTitles();
|
||
|
// 按 `Priority` 常量值排序
|
||
|
result.Sort((a, b) => GetPriority(a).CompareTo(GetPriority(b)));
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
private int GetPriority(Type type)
|
||
|
{
|
||
|
// 获取 `Priority` 常量字段
|
||
|
var field = type.GetField(Priority, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy
|
||
|
| BindingFlags.NonPublic);
|
||
|
|
||
|
// 确保字段存在且是 `int`
|
||
|
if (field != null && field.FieldType == typeof(int))
|
||
|
{
|
||
|
// Console.WriteLine((int)field.GetValue(null)!);
|
||
|
return (int)field.GetValue(null)!; // 获取静态字段的值
|
||
|
}
|
||
|
return int.MaxValue; // 如果没有 `Priority`,默认放到最后
|
||
|
}
|
||
|
|
||
|
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
|
||
|
public string[] GetTitles()
|
||
|
{
|
||
|
List<string> list = [];
|
||
|
foreach (var type in result)
|
||
|
{
|
||
|
string Title;
|
||
|
// 获取静态字段 Title
|
||
|
FieldInfo titleSField = type.GetField("Title", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy
|
||
|
| BindingFlags.NonPublic);
|
||
|
if (titleSField != null)
|
||
|
{
|
||
|
// 获取静态字段的值
|
||
|
Title = (string)titleSField.GetValue(null); // 静态字段传 null
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
Title = type.Name;
|
||
|
}
|
||
|
// Console.WriteLine("正在搜索:" + Title);
|
||
|
list.Add(Title ?? "null");
|
||
|
}
|
||
|
return [.. list];
|
||
|
}
|
||
|
}
|