簡體   English   中英

獲取基類中派生類的類類型,並將其作為類型參數傳遞

[英]Get class type of derived class in base class and pass it as a type parameter

我有一個基礎班“ Powerup”,然后是該班“炸彈”,“擊退”和“牆”的三個孩子。

在基類中,我想獲取派生類類型,以便可以將其作為方法參數傳遞。

在這一刻,我通過使用如下代碼解決了這個問題:

if (this is BombPowerup)
   AddComponent<BombPowerup>();
else if (this is RepelPowerup)
   AddComponent<RepelPowerup>();
else if (this is WallPowerup)
   AddComponent<WallPowerup>();

但這並不是真正可擴展的。 我知道我可以創建一個抽象方法並讓子類自己完成每一行,但是我想知道我可以在基類中使用的解決方案來進行良好的學習。

謝謝。

編輯:方法AddComponent定義如下

void AddComponent<T>() where T : Powerup

您可以使用反射來做到這一點:

var method = typeof(Powerup).GetMethod("AddComponent").MakeGenericMethod(this.GetType());
method.Invoke(this, new object[]);

或者,您可以在基類中添加通用類型參數,然后使用該參數來調用AddComponent

public abstract class Powerup<T> where T : Powerup
{
    private void AddSelf()
    {
        this.AddComponent<T>();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM