场景:类似与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();
}