C#调用基础构造函数

时间:2014-02-20 12:15:19

标签: c# inheritance constructor

我已经谷歌“调用基础构造函数”了,我没有得到我需要的答案。

这是我的构造函数;

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

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

现在我有了这个,我想继承构造函数及其所有工作。 这是我期望做的;

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

为什么我不能这样做?

4 个答案:

答案 0 :(得分:6)

使用: base()

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

或带参数:

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

答案 1 :(得分:1)

  

为什么要隐藏一个继承的成员?

因为我打赌基类中的方法没有标记为virtual


我看到你删除了问题的那一部分。嗯,我现在已经回答了它......

答案 2 :(得分:0)

您的代码中存在多个问题。它应该是这样的

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

答案 3 :(得分:0)

调用基类的构造函数:

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

要覆盖update方法,必须在基类中将其声明为虚拟:

public virtual void update() { .. }
相关问题