2012-03-24 52 views
1

我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類構造函數。

感謝

回答

3

首先要從兩個類這將是非法的繼承。

由於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= .... 

    } 
    ..................... 
} 
1

繼承BigRedBird。通過這樣做,您仍然可以訪問GameComponent中的內容,因爲Bird從它繼承。

順便說一句,在C#中不能繼承多個類。

2

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 
     ... 
    } 
} 
相關問題