【问题标题】:Why does DrawableGameComponent need to call base.Draw()?为什么 DrawableGameComponent 需要调用 base.Draw()?
【发布时间】:2015-03-11 21:53:22
【问题描述】:

我正在 XNA / Monogame 框架中创建一个基本游戏。我使用 DrawableGameComponent 以便自动调用它的 Draw() 和 Update() 函数。

到目前为止,一切都很好,但我不明白 base.Draw() 在 DrawableGameComponent 实例中指的是什么,以及为什么需要它。在我的示例中,我什至可以省略它,游戏仍然可以正常运行。

代码摘录:(cmets中的问题)

Game1.cs

 protected override void Initialize()
        {
            Car car3 = new Car(this, new Vector2(450, 100), Color.GreenYellow);
            base.Initialize();
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            SpriteBatch.Begin();
            // this calls Game.Draw - and this loops through all the game components and draws them
            base.Draw(gameTime);
            SpriteBatch.End();
        }

还有 Car.cs

public override void Draw(GameTime gameTime)
        {
            // this draws the car after Car.Draw() gets called by the Game class
            Game1.SpriteBatch.Draw(Texture,Position,Color);

            // but why do we call base.Draw here? The car is already drawn. 
            // and the DrawableGameComponent.Draw method is empty, so we dont really need to call that?
            // what's more, if I comment this code out, the game still works.
            base.Draw(gameTime);
        }

【问题讨论】:

    标签: c# xna


    【解决方案1】:

    可能是因为如果您开始扩展 Car 类,例如,raceCar、bigCar 等,您可能不想重新编码您在基类汽车类中编写的绘图函数语句。这就是在 POO 编程中使用 base.Draw() 或 base 的主要原因。

    【讨论】:

    • 是的,但在这种情况下,我们讨论的是直接从 DrawableGameComponent 继承的最上层类。在该组件中,draw 函数为空,因此无需使用 base.Draw() 调用它。 --- 这实际上是我自己问题的答案。 base.Draw() 可以安全地删除。
    【解决方案2】:

    回答我自己的问题:一旦您从类继承并覆盖函数,编辑器就会自动插入 base.Draw() 行。

    在这种情况下,父类在 Draw() 中没有任何代码,因此无需从子类的 Draw 函数中调用 base.Draw()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 2018-01-03
      • 2019-06-09
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多