[英]How can I inherit all properties from all Base classes in C#
I have XNA game and it contains these classes 我有XNA游戏,其中包含这些类
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
}
.....................
}
How can I access Position and velocity from Bird Class and use it in BigRedBird Class in the constructor. 如何从Bird类访问位置和速度,并在构造函数的BigRedBird类中使用它。
Thanks 谢谢
To start with you are inheriting from two classes which would be illegal. 首先,您要从两个非法类继承。
As Bird already inherits from GameComponent its not a problem that you don't mention it in BigRedBird it's already inherited through bird! 因为Bird已经从GameComponent继承了,所以您在BigRedBird中没有提到它不是问题,它已经通过bird继承了!
As BigRedBird inherits from Bird it will have all its properties so you just need to do 由于BigRedBird从Bird继承而来,它将具有其所有属性,因此您只需要
public class BigRedBird : Bird
{
public BigRedBird(Game game ,Rectangle area,Texture2D image)
: base(game)
{
// TODO: Construct any child components here
this.Position= ....
}
.....................
}
C# doesn't support multiple inheritance, so the answer to the question in your title is - you can't. C#不支持多重继承,因此标题中问题的答案是-您不能。 But I don't think that's what you were trying to achieve.
但是我认为这不是您要实现的目标。
Add suitable constructors to your Bird class: 将适当的构造函数添加到Bird类:
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;
...
}
}
And then call the base class constructor in your derived class 然后在派生类中调用基类构造函数
public class BigRedBird : Bird
{
public BigRedBird( Game game, ... ) : base(game, ... )
{
}
}
Or 要么
public class BigRedBird : Bird
{
public BigRedBird( Game game, ... ) : base(game)
{
base.Velocity = ...; // note: base. not strictly required
...
}
}
Inherit BigRedBird
from Bird
only. BigRedBird
Bird
继承BigRedBird
。 By doing that, you will still be able to access stuff from GameComponent
, since Bird
inherits from it. 这样,由于
Bird
继承自GameComponent
,因此您仍然可以从GameComponent
进行访问。
By the way, inheriting from multiple classes is not possible in C#. 顺便说一下,在C#中不可能从多个类继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.