- 最后登录
- 2021-7-6
- 注册时间
- 2012-12-27
- 阅读权限
- 90
- 积分
- 76145
- 纳金币
- 53456
- 精华
- 316
|
获得所有继承自BaseType的类,并将他们的方法保存到字典中。- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- public class BaseClass
- {
- public string cName = "BaseClass";
- public virtual string GetName()
- {
- return cName;
- }
- }
- public class NewClass1 : BaseClass
- {
- private static string cName = "NewClass1";
- public override string GetName()
- {
- return cName;
- }
- }
- public class NewClass2 : BaseClass
- {
- private static new string cName = "NewClass2";
- public override string GetName()
- {
- return cName;
- }
- }
- public class ClassTest : MonoBehaviour
- {
- public delegate string GetEvent();
- public Dictionary<string, GetEvent> dic = new Dictionary<string, GetEvent>();
- void Init()
- {
- Type[] arr = GetChildTypes(typeof(BaseClass));
- foreach(Type t in arr)
- {
- object obj = Activator.CreateInstance(t);
- BaseClass bc = obj as BaseClass;
- if (!dic.ContainsKey(bc.GetName()))
- dic.Add(bc.GetName(), null);
- dic[bc.GetName()] += bc.GetName;
- }
- }
- // 获取继承 baseType 的所有类型
- private Type[] GetChildTypes(Type baseType)
- {
- List<Type> listType = new List<Type>();
- Assembly assem = Assembly.GetAssembly(baseType);
- foreach (Type tChild in assem.GetTypes())
- {
- if (tChild.BaseType == baseType)
- {
- listType.Add(tChild);
- }
- }
- return listType.ToArray();
- }
- }
复制代码 最近在做服务器下发指令之后客户端对应做操作,每条新的指令都需要新建一个文件来写发送和接收。
接收方式是收到消息之后根据消息明,在保存的 <消息名, 消息回调> 字典里调用对应回调函数。
为了不要每次新增一个命令就手动写一条保存,而且也很可能会遗漏,因此做法就是所有命令类都继承 CmdBase , 并且在网络初始化的时候先
获取所有继承自 BaseClass,之后将回调保存到字典中
|
|