C#虚拟方法

时间:2015-08-06 09:17:36

标签: c# c++ oop inheritance virtual

在C ++中,我能够做到这一点

class App
{
public:
    virtual void OnMouseMove(etc);
    void FunctionThatDoesStuff();
};

void App::FunctionThatDoesStuff()
{
    // Engine stuff here
    OnMouseMove(etc);
}

class ProjectName : public App
{
public:
    void OnMouseMove(etc);
};

void ProjectName::OnMouseMove(etc)
{
    // User stuff here
}

然后当从App中的FunctionThatDoesStuff调用OnMouseMove时,它将被覆盖并且它将调用ProjectName.OnMouseMove。但是在C#中我无法做到这一点。这是我的第一次尝试。

public class App
{
    protected void MouseMove()
    {
        // Engine code here
        OnMouseMove(etc);
    }

    protected virtual void OnMouseMove(etc)
    {
        // Do Nothing
    }
}

public class ProjectName : App
{
    protected override void OnMouseMove(etc)
    {
        // User code here
    }
}

我尝试使用委托,因为它们只是未实现的功能。但这并没有奏效。我怎样才能在C#中实现等效?我想我可以解决它并使用事件。但有没有更类似的方法来做到这一点。

2 个答案:

答案 0 :(得分:1)

我们假设您在MouseMove类中拥有默认的App实现。

public abstract class App
{
    protected void MouseMove()
    {
        // Engine code here
    }

    protected virtual void OnMouseMove(object etc)
   {

   // Default implementation here
    Console.WriteLine('A');

   }
}

然后你有第二个班ProjectName和另一个实现

public class ProjectName : App
{
    protected override void OnMouseMove(etc)
    {
        // Overrride implementation

         Console.WriteLine('B')
    }
}

然后当你有类型为App的对象时,它将打印A 当你有类型的对象:' ProjectName'它会打印B

    var app = new App();

    var project = new ProjectName();

    app.OnMouseMove();
// Will Print A

    project.OnMouseMove();
// Will Print B

答案 1 :(得分:0)

如果我理解你在谈论抽象方法或类:

public abstract class App
{
    protected void MouseMove()
    {
        // Engine code here
    }

    protected abstract void OnMouseMove(object etc);
}

public class ProjectName : App
{
    protected override void OnMouseMove(object etc)
    {
        // User code here
    }
}