【问题标题】:Get class type of derived class in base class and pass it as a type parameter获取基类中派生类的类类型并将其作为类型参数传递
【发布时间】:2013-12-15 17:33:30
【问题描述】:

我有一个基类“Powerup”,然后是该类“Bomb”、“Repel”和“Wall”的 3 个子类。

在基类中,我想获取派生类类型,以便可以将其作为方法参数传递。

现在我使用如下代码解决了这个问题:

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

【问题讨论】:

  • 贴出AddComponent方法的定义。另外,应该为每个后代类调用AddComponent,还是应该省略一些后代?
  • 每个后代班级。 AddComponent 只是一个具有泛型类型的方法,其中类型继承自 Powerup

标签: c# inheritance


【解决方案1】:

你可以使用反射来做到这一点:

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>();
    }
}

【讨论】:

  • 看起来合法,感谢您的回答。当我早上在电脑前时会检查它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 2021-10-25
  • 2015-03-30
  • 2014-04-11
  • 2021-02-13
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多