覆盖已经重写的虚拟函数

时间:2013-11-12 01:07:40

标签: c# inheritance

我试图覆盖/重载已在基类中重写的虚函数。为了更好地理解我想要做什么,请查看以下示例:

public class Parent
{
    public virtual void foo() {
        print("Parent::foo()");
    }
}

public class Derived : Parent
{
    public override void foo() {
        print("Derived::foo()");
    }
}

public class Child : Derived
{
    public override void foo() {
        print("Child::foo()");
    }
}


// When I create an instance of Child and call the method foo, 
// it calls the Derived::foo() method and not Child::foo()
// How can I make Child override Derived::foo()?

是否可以覆盖Derived :: foo()?如果不是,你会怎么建议我解决这个问题?

2 个答案:

答案 0 :(得分:2)

这会在C#中调用Child::foo。试试这段代码:

class Program {
    static void Main()
    {
        Parent foo = new Child();
        foo.foo();
    }
}

// Define other methods and classes here
public class Parent
{
    public virtual void foo() {
        Console.WriteLine("Parent::foo()");
    }
}

public class Derived : Parent
{
    public override void foo() {
        Console.WriteLine("Derived::foo()");
    }
}

public class Child : Derived
{
    public override void foo() {
        Console.WriteLine("Child::foo()");
    }
}

这将运行并打印Child::foo()

答案 1 :(得分:0)

如果没有看到您的调用代码,我无法肯定地说,但您确定没有犯错并创建Derived的实例吗?