C# 基于反射自动绑定回调

场景:类似与web开发中的API自动注册功能,自动将指定类的所有方法与一个回调码绑定,核心代码如下

string listenerMethodPrefix="_";
/// <summary>
/// 根据MsgListener的方法与回调码    进行绑定
/// 规则自动将规则码前加一个listenerMethodPrefix字符串,如: RequireCode.RobotCatch ==  MsgListener._RobotCatch
/// </summary>
private static void RegisterMsgListener()
{
    Type ListenerType = typeof(MsgListener);
    Action<RequireCode, Action<string>> action = AddMsgListener;
    MethodInfo[] ms = ListenerType.GetMethods(BindingFlags.Public | BindingFlags.Static);
    Dictionary<string, MethodInfo> mk = ms.ToDictionary(m => m.Name);

    foreach (var item in Enum.GetNames(typeof(RequireCode)))
    {
        RequireCode a = (RequireCode)Enum.Parse(typeof(RequireCode), item);
        ms.ToList().ForEach(m =>
        {
            if (m.Name.StartsWith(listenerMethodPrefix)
                && m.Name.IndexOf(a.ToString()) != -1
                )
            {
                action(a, (Action<string>)Action.CreateDelegate(typeof(Action<string>), m));
            }
        });
    }
}

MsgListener样例如下:

    public class MsgListener
    {
        public static void _None(CommutBase value)
        {
            Debug.Log($"None:{JsonConvert.SerializeObject(value)}");
        }
        public static void _HeartBeart(CommutBase value)
        {
            Debug.Log($"HeartBeart:{value?.ToString()}");
        }
        public static void _Pong(CommutBase value)
        {
            NetManagerClient.lastPongTime = Time.time;
        }
        public static void _Ping(CommutBase value)
        {
            //Debug.Log($"Ping:{value?.ToString()}");
        }

    }

RequireCode:


public enum RequireCode
{
    None = 0,
    Pong ,
    Ping ,
    HeartBeart
}

如果需要自动绑定所有的类的方法,建议controller类统一实现一个Api接口,通过反射的方法获取到类的集合,然后使用上面的自动注册方法RegisterMsgListener注册对应的方法,获取所有的类的方法如下:

public interface IAutoMap
        {
        }


        void Demo()
        {
            List<Type> types = GetSubClassTypes(typeof(IAutoMap));
        }
        /// <summary>
        /// C#获取一个接口在所在的程序集中的所有子类
        /// </summary>
        /// <param name="parentType">接口</param>
        /// <returns>所有子类的名称</returns>
        public static List<Type> GetSubClassTypes(Type parentType)
        {
            List<Type> subTypeList = new List<Type>();
            var assembly = parentType.Assembly;//获取当前接口所在的程序集``
            var assemblyAllTypes = assembly.GetTypes();//获取该程序集中的所有类型
            foreach (var itemType in assemblyAllTypes)//遍历所有类型进行查找
            {
                var baseInteface = itemType.GetInterfaces();
                if (baseInteface != null && baseInteface.Length > 0)
                {
                    foreach (var itemInterface in baseInteface)
                    {
                        if (itemInterface.Name == parentType.Name)
                        {
                            subTypeList.Add(itemType);//加入子类集合中
                            break;
                        }
                    }
                }
            }
            return subTypeList;//获取所有子类类型的名称
        }
        // Update is called once per frame
        /// <summary>
        /// C#获取一个接口在所在的程序集中的所有子类类型的名称
        /// </summary>
        /// <param name="interfaceMethod">给定的类型</param>
        /// <returns>所有子类类型的名称</returns>
        public static List<string> GetSubClassNames(Type interfaceMethod)
        {
            return GetSubClassTypes(interfaceMethod).Select(i => i.Name).ToList();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值