C#获取所有继承抽象类的子类

您所在的位置:网站首页 查看一个类的子类 C#获取所有继承抽象类的子类

C#获取所有继承抽象类的子类

2024-05-01 03:22| 来源: 网络整理| 查看: 265

有时做sdk或者插件时需要在sdk里写下基类,又要允许用户继承基类后能在不手动注册的情况下能自动替换执行用户实现的类。所以sdk里需要根据查找有哪些继承了基类了子类进行自动注册。然后讲所有子类名称为key 子类type为value保存在sdk的类字典中待用。

void Start () { //var types = Assembly.GetEntryAssembly().GetTypes(); var types = Assembly.GetCallingAssembly().GetTypes(); var aType = typeof(A); Debug.Log(aType.FullName); List alist = new List(); foreach (var type in types) { var baseType = type.BaseType; //获取基类 while (baseType != null) //获取所有基类 { Debug.Log(baseType.Name); if (baseType.Name == aType.Name) { Type objtype = Type.GetType(type.FullName, true); object obj = Activator.CreateInstance(objtype); if (obj != null) { A info = obj as A; alist.Add(info); } break; } else { baseType = baseType.BaseType; } } } foreach (var item in alist) { item.a();//执行方法 } }

然后建几个类测试一下

public abstract class A { public abstract void a(); } public class AA:A { public override void a() { Debug.Log("AA......."); } } public class BB : A { public override void a() { Debug.Log("BB......."); } } public class CC : A { public override void a() { Debug.Log("CC......."); } }

这样就可以调用所有子类中的a方法了

一下是从字典里获取Type然后实例化的方法

#region 公用函数 public EffectScriptBase CreateScript(GameObject obj,string ScriptID) { EffectScriptBase flag = null; //flag = XSkillManager.CreateClone(ScriptID); //switch (ScriptID) //{ // case "ESLineToObject": // flag = obj.AddComponent(); // break; //} if (ScriptID.Length > 0 && CSkillCore.Instance.EffectScriptMap.ContainsKey(ScriptID)) { Type t = CSkillCore.Instance.EffectScriptMap[ScriptID]; if (t != null) { flag = obj.AddComponent(t) as EffectScriptBase; } } return flag; } #endregion

 

重新封装了一个函数:只是为了方便测试,跟上面功能一模一样。

public Dictionary LoadBuffScript(Type _type) { Dictionary list = new Dictionary(); var types = Assembly.GetCallingAssembly().GetTypes(); //var aType = typeof(IBuffControl); var aType = _type; foreach (var type in types) { var baseType = type.BaseType; //获取基类 while (baseType != null) //获取所有基类 { //Debug.Log(baseType.Name); if (baseType.Name == aType.Name) { Type objtype = Type.GetType(type.FullName, true); //object obj = Activator.CreateInstance(objtype); //if (obj != null) //{ //SeekTarget info = obj as SeekTarget; list.Add(objtype.Name, objtype); //} break; } else { baseType = baseType.BaseType; } } } return list; }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3