【发布时间】:2014-04-11 16:28:00
【问题描述】:
在我的游戏中实现继承时遇到了一些麻烦。我认为最好引入继承,因为它会使我的代码更整洁,更有条理。
我在atm面临的问题是从派生类中的基类调用构造函数时的参数。
我使用 Paddle 类作为基类,Player 类作为继承 Paddle 的类。
代码如下:
在 Paddle 类中......
//properties
protected Texture2D pTexture;
protected Vector2 pPosition;
protected Vector2 pVelocity;
//constructor for Paddle class (only first line here, as the rest is irrelevant)
public Paddle(Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour)
在 Player 类中......
//properties
PlayerIndex pID;
//constructor for Player class (only first line here, as the rest is irrelevant)
public Player(PlayerIndex newID) : base()
在你提到它不工作的原因之前,因为我在 Player 类中调用的基构造函数没有任何参数,而基类/Paddle 类中的构造函数有,我理解这一点。我面临的问题是设置播放器的纹理、位置等,但纹理、位置等在基类中,因为它们是 Player 和 Enemy 类的通用属性(另一个继承自 Paddle 的类,但它是相似的给玩家,因此现在只提到它)。在 Player 类中调用基构造函数时,我也不知道该放什么作为参数。
感谢您的阅读和提前帮助:-)
添加的代码我已更改如下:
public Player(PlayerIndex newID, Texture2D newTexture, Vector2 newPosition, Viewport theViewport, Color newColour)
: base(newTexture, newPosition, theViewport, newColour)
【问题讨论】:
-
如果您不确定,那么我相信您的继承结构有误。您当前的代码是说玩家类将具有 Paddle 类的所有属性,但看起来并非如此。
-
有什么问题?你知道为什么它不起作用。那么为什么不直接传递所需的参数来使其工作呢?
标签: c# class inheritance constructor xna