繁体   English   中英

C#调用基本构造函数

[英]C# Calling base constructor

我有Google的“调用基础构造函数”,但没有得到所需的答案。

这是我拥有的构造函数;

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
}

我为什么不能这样做?

用途: 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)
    {}
}

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

因为我敢打赌,基类中的方法未标记为virtual


我看到您删除了问题的这一部分。 好吧,我现在已经回答了...

您的代码中有多个问题。 应该是这样

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

调用基类的构造函数:

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

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

public virtual void update() { .. }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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