Files
Gen_Hack-and-Slash-Roguelite/Client/Assets/Scripts/Parsing/HediffCompParsing.cs

85 lines
4.1 KiB
C#
Raw Normal View History

using System;
using HediffComps;
using UnityEngine;
namespace Parsing
{
public static class HediffCompParsing
{
/// <summary>
/// 在当前应用程序域的加载程序集中查找指定名称的类型。
/// </summary>
/// <param name="typeFullName">要查找的类型的完整名称。</param>
/// <param name="baseType">期望的基类 Type。</param>
/// <returns>如果找到符合条件的类型则返回其 Type 对象;否则返回 null。</returns>
private static Type FindTypeInAssemblies(string typeFullName, Type baseType)
{
// 遍历所有已加载的程序集
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
// 尝试从程序集中获取类型,不抛出异常,忽略大小写
var foundType = assembly.GetType(typeFullName, false, true);
// 检查找到的类型是否符合条件:
// 1. 类型不为 null
// 2. 是基类或其子类
// 3. 不是抽象类(可实例化)
// 4. 具有公共的无参数构造函数
if (foundType != null &&
baseType.IsAssignableFrom(foundType) &&
!foundType.IsAbstract &&
foundType.GetConstructor(Type.EmptyTypes) != null)
return foundType;
}
return null; // 未找到符合条件的类型
}
/// <summary>
/// 根据给定的字符串名称解析并返回 HediffComps.HediffComp 的实例化子类。
/// </summary>
/// <param name="hediffCompName">HediffComp 子类的名称,可能包含命名空间。</param>
/// <returns>实例化后的 HediffComps.HediffComp 子类对象;如果找不到或无法实例化,则返回 null。</returns>
public static HediffComp ParseHediffComp(string hediffCompName)
{
// 如果输入名称为空或空白,直接返回 null
if (string.IsNullOrWhiteSpace(hediffCompName)) return null;
// 获取 HediffComps.HediffComp 的 Type 对象,作为查找的基准
var baseHediffCompType = typeof(HediffComp);
Type targetType = null;
// 1. 如果 hediffCompName 包含点号 '.',则尝试将其作为完整的类型名称(包含命名空间)查找。
if (hediffCompName.Contains(".")) targetType = FindTypeInAssemblies(hediffCompName, baseHediffCompType);
// 2. 如果之前未找到,或者 hediffCompName 不包含点号,则尝试默认命名空间查找。
if (targetType == null)
{
// 尝试在 HediffComps 命名空间下查找
// 构建完整的类型名称,例如 "HediffComps.MyHediffComp"
var hediffCompsNamespaceName = baseHediffCompType.Namespace + "." + hediffCompName;
targetType = FindTypeInAssemblies(hediffCompsNamespaceName, baseHediffCompType);
}
// 3. 如果前两种尝试仍未找到,则尝试在无命名空间(全局或根命名空间)下查找。
if (targetType == null) targetType = FindTypeInAssemblies(hediffCompName, baseHediffCompType);
// 如果成功找到一个符合条件的类型,则尝试实例化它。
if (targetType != null)
try
{
// 使用 Activator.CreateInstance 调用类型的无参数构造函数创建实例
return (HediffComp)Activator.CreateInstance(targetType);
}
catch (Exception ex)
{
// <color=red>实例化 HediffComp '{hediffCompName}' (Type: '{targetType.FullName}') 时出错: {ex.Message}</color>
Debug.LogError(
$"<color=red>实例化 HediffComp '{hediffCompName}' (Type: '{targetType.FullName}') 时出错: {ex.Message}</color>");
return null;
}
// 如果所有查找和实例化尝试都失败,返回 null
return null;
}
}
}