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


随便建一个类

写上方法

    void Start () 
    {
        //var types = Assembly.GetEntryAssembly().GetTypes();
       var types = Assembly.GetCallingAssembly().GetTypes();
        var aType = typeof(A);
        Debug.Log(aType.FullName);
        List<A> alist = new List<A>();
        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方法了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM