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