简体   繁体   中英

How can I inherit all properties from all Base classes in C#

I have XNA game and it contains these classes

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.

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!

As BigRedBird inherits from Bird it will have all its properties so you just need to do

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. But I don't think that's what you were trying to achieve.

Add suitable constructors to your Bird class:

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. By doing that, you will still be able to access stuff from GameComponent , since Bird inherits from it.

By the way, inheriting from multiple classes is not possible in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM