简体   繁体   English

C#调用基本构造函数

[英]C# Calling base constructor

I've Google'd "calling base constructor", and I'm not getting the answers I need. 我有Google的“调用基础构造函数”,但没有得到所需的答案。

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() : 用途: 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 . 因为我敢打赌,基类中的方法未标记为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: 要覆盖update方法,必须在基类中将其声明为virtual:

public virtual void update() { .. }

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

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