我如何继承在C#中的所有基类的所有属性
问题描述:
我XNA游戏,它包含这些类我如何继承在C#中的所有基类的所有属性
public partial class Bird : Microsoft.Xna.Framework.GameComponent
{
private Vector2 velocity;
private Vector2 position;
..........................
public Vector2 Velocity
{
get { return velocity; }
set { velocity = value; }
}
public Vector2 Position
{
get { return position; }
set { position = value; }
}
}
public class BigRedBird : Microsoft.Xna.Framework.GameComponent,Bird
{
public BigRedBird(Game game ,Rectangle area,Texture2D image)
: base(game)
{
// TODO: Construct any child components here
}
.....................
}
如何从鸟级接入位置和速度,并在 使用它BigRedBird类构造函数。
感谢
答
首先要从两个类这将是非法的继承。
由于Bird已经从GameComponent继承,它不是一个你没有在BigRedBird中提及它的问题,它已经通过bird继承了!
由于BigRedBird从鸟继承它有它的所有属性,所以你只需要从只Bird
做
public class BigRedBird : Bird
{
public BigRedBird(Game game ,Rectangle area,Texture2D image)
: base(game)
{
// TODO: Construct any child components here
this.Position= ....
}
.....................
}
答
继承BigRedBird
。通过这样做,您仍然可以访问GameComponent
中的内容,因为Bird
从它继承。
顺便说一句,在C#中不能继承多个类。
答
C#不支持多继承,所以标题中问题的答案是 - 你不能。但我不认为这就是你想要达到的目标。
适合构造添加到您的鸟类:
public partial class Bird : Microsoft.Xna.Framework.GameComponent
{
public Bird(Game game) : base(game)
{
}
public Bird(Game game, Vector2 velocity, Vector2 position) : base(game)
{
Velocity = velocity;
...
}
}
然后调用基类的构造函数在派生类中
public class BigRedBird : Bird
{
public BigRedBird(Game game, ...) : base(game, ...)
{
}
}
或者
public class BigRedBird : Bird
{
public BigRedBird(Game game, ...) : base(game)
{
base.Velocity = ...; // note: base. not strictly required
...
}
}