[英]How can I recursively search properties in C# only if those properties inherit from some base class?
[英]How can I inherit all properties from all Base classes in C#
我有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
}
.....................
}
如何從Bird類訪問位置和速度,並在構造函數的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= ....
}
.....................
}
C#不支持多重繼承,因此標題中問題的答案是-您不能。 但是我認為這不是您要實現的目標。
將適當的構造函數添加到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;
...
}
}
然后在派生類中調用基類構造函數
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
...
}
}
BigRedBird
Bird
繼承BigRedBird
。 這樣,由於Bird
繼承自GameComponent
,因此您仍然可以從GameComponent
進行訪問。
順便說一下,在C#中不可能從多個類繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.