为什么DrawableGameComponent可以使用实例类
本文关键字:实例 可以使 DrawableGameComponent 为什么 | 更新日期: 2023-09-27 17:49:14
我注意到DrawableGameComponent
可以用于"实例类"
DrawableGameComponent
包含一些"覆盖",如Draw
, LoadContent
, Update
等。看看下面的代码:
public class Game1 : Microsoft.Xna.Framework.Game
{
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Contenttt";
graphics.PreferredBackBufferWidth = GAME_WIDTH;
graphics.PreferredBackBufferHeight = GAME_HEIGHT;
}
}
另一个类的代码:
public class Bullet: DrawableGameComponent //based by DrawableGameComponent
{
public Bullet(Game1 game): base(game) //set argument for draablegamecomponent
{
//do something
}
}
DrawableGameComponent:
public DrawableGameComponent (Game Game )
参数描述:
游戏类型:游戏游戏组件应该附加到的游戏。**
可以看到,DrawableGameComponent
的参数是Microsoft.Xna.Framework.Game
的一个类。然后我们用Game1
类填充它。
这是我的其他职业的代码,将影响我的World Game1 DrawableGameComponent
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
}
protected override void UnloadContent()
{
}
问题是:为什么我们可以在我自己的类上使用它们的"重写"?为什么这会影响游戏世界?
然而,在c#中,像
这样的"基"语句公共类Bullet: MyClass
我们不能让它基于"instance"类。
但是对于DrawableGameComponent
,实例类,他们可以通过他们的参数设置它,所以他们的"override void"将对我们之前设置的参数类起作用。
如果你知道怎么做,请告诉我怎么做。
听起来您可能不理解virtual
方法的概念。override
方法的功能是可用的,因为在基类中定义的方法被标记为virtual
。基本上这些都是模板方法设计模式的例子。virtual
或abstract
方法允许在子类中更改它们的实现(或者在抽象类的情况下,完全不同)。
public abstract class BaseClass
{
public void TemplateMethod()
{
DoSomething();
DoSomethingElse();
}
protected virtual void DoSomething()
{
// implementation that can be changed or extended
}
// no implementation; an implementation must be provided in the inheritor
protected abstract void DoSomethingElse();
}
public sealed class SubClass : BaseClass
{
protected override DoSomething()
{
// add extra implementation before
base.DoSomething(); // optionally use base class' implementation
// add extra implementation after
}
protected override DoSomethingElse()
{
// write an implementation, since one did not exist in the base
}
}
那么你可以这样做:
SubClass subClass = new SubClass();
// will call the new implementations of DoSomething and DoSomethingElse
subClass.TemplateMethod();
参见:
- 继承虚拟方法
- 方法模板