c#反射Action

using System;

namespace Buff
{
    class BuffEvents
    {
        // 生命周期
        static public Action OnCreated = delegate { }; // 创建时,插入前
        static public Action OnStart = delegate { }; // 创建,插入后
        static public Action OnEnd = delegate { }; // 结束
        static public Action OnDestroy = delegate { }; // 销毁时
        static public Action OnIntervalThink = delegate { }; // 间隔触发

        // 全局钩子
        static public Action OnAttack = delegate { }; // 攻击时
        static public Action OnAttackLanded = delegate { }; // 攻击到某个目标时
        static public Action OnAttacked = delegate { }; // 被攻击时
        static public Action OnKill = delegate { }; // 击杀目标
        static public Action OnDeath = delegate { }; // 死亡时


        static public System.Reflection.FieldInfo GetField(string eventName)
        {
            if (eventName == "" || eventName == null) return null;

            var type = typeof(BuffEvents);
            var field = type.GetField(eventName);
            return field;
        }

        static public Action GetAction(string eventName)
        {
            var field = GetField(eventName);
            if (field == null) return null;

            var action = (Action)field.GetValue(null);
            return action;
        }

        static public void InvokeAction(string eventName, string str)
        {
            var action = GetAction(eventName);
            if (action == null) return;
            action();
        }

        static public void AddAction(string eventName, Action action)
        {
            var oldAction = GetAction(eventName);
            if (oldAction == null) return;

            var field = GetField(eventName);
            field.SetValue(oldAction, oldAction + action);
        }

        static public void RemoveAction(string eventName, Action action)
        {
            var oldAction = GetAction(eventName);
            if (oldAction == null) return;

            var field = GetField(eventName);
            field.SetValue(oldAction, oldAction - action);
        }

    }
}
posted @ 2023-03-06 21:09  _NKi  阅读(71)  评论(0编辑  收藏  举报