简体   繁体   中英

C# Calling base constructor

I've Google'd "calling base constructor", and I'm not getting the answers I need.

Here's the constructor I have;

public class defaultObject
{
    Vector2 position;
    float rotation;
    Texture2D texture;

    public defaultObject(Vector2 nPos, float nRotation, Texture2D nTexture)
    {
        position = nPos;
        rotation = nRotation;
        texture = nTexture;
    }
}

Now I have that in place, I want to inherit the constructor and all its workings. This is what I'd expect to do;

public class Block : defaultObject
{
    // variables inherited from defaultObject
    public Block : defaultObject; //calls defaultObject constructor
}

Why can't I do that?

Use : base() :

public class Block : defaultObject
{
    // variables inherited from defaultObject
    public Block ()
        : base()
    {}
}

or with parameters:

public class Block : defaultObject
{
    // variables inherited from defaultObject
    public Block (Vector2 nPos, float nRotation, Texture2D nTexture)
        : base(nPos, nRotation, nTexture)
    {}
}

Why is it hiding an inherited member?

Because I bet the method in the base class is not marked virtual .


I see that you removed that part of the question. Well, I've answered it anyway now...

you have multiple problems in your code. It should be like this

public Block(Vector2 nPos, float nRotation, Texture2D nTexture) : base(nPos,nRotation,nTexture) // see the way params are passed to the base constructor
{}

To call the base class's constructor:

public class Block : defaultObject
{
    // variables inherited from defaultObject
    public Block(npos, rotation, texture) : base(npos, rotation, texture); //calls defaultObject constructor
}

To override the update method, you must declare it virtual in the base class:

public virtual void update() { .. }

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