59 lines
2.0 KiB
C#
59 lines
2.0 KiB
C#
/*
|
||
* @Author: 白哉
|
||
* @Description: 技能工厂类
|
||
* @Date: 2025年04月24日 星期四 17:04:55
|
||
* @Modify:
|
||
*/
|
||
|
||
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq.Expressions;
|
||
using System.Reflection;
|
||
|
||
|
||
namespace Logic.Skill
|
||
{
|
||
public class SkillFactory
|
||
{
|
||
// 使用编译后的工厂委托替代 Activator.CreateInstance,消除反射开销
|
||
private static Dictionary<SkillType, Func<SkillBase>> _skillFactoryDict;
|
||
|
||
|
||
public static SkillBase GetSkillBySkillType(SkillType skillType)
|
||
{
|
||
if (_skillFactoryDict == null)
|
||
{
|
||
_skillFactoryDict = new Dictionary<SkillType, Func<SkillBase>>();
|
||
Assembly assembly = typeof(SkillBase).Assembly;
|
||
foreach (Type skillClassType in assembly.GetTypes())
|
||
{
|
||
if (skillClassType.IsSubclassOf(typeof(SkillBase)) && !skillClassType.IsAbstract)
|
||
{
|
||
var ctor = skillClassType.GetConstructor(Type.EmptyTypes);
|
||
if (ctor == null) continue;
|
||
// 编译 () => new ConcreteSkillType() 委托,后续调用零反射
|
||
var factory = Expression.Lambda<Func<SkillBase>>(
|
||
Expression.New(ctor)).Compile();
|
||
var tmpSkill = factory();
|
||
if (tmpSkill == null) continue;
|
||
_skillFactoryDict[tmpSkill.GetSkillType()] = factory;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (_skillFactoryDict.TryGetValue(skillType, out var skillFactory))
|
||
{
|
||
var skillObj = skillFactory();
|
||
if (skillObj != null && Table.Instance.SkillDataAssets.GetSkillInfo(skillType, out var skillInfo))
|
||
{
|
||
skillObj.SetSkillPriority(skillInfo.skillPriority);
|
||
}
|
||
return skillObj;
|
||
}
|
||
|
||
return null;
|
||
}
|
||
}
|
||
}
|