C# 重写已被重写的虚拟函数
我试图重写/重载已在基类中重写的虚拟函数。为了更好地理解我想做什么,请看以下示例:C# 重写已被重写的虚拟函数,c#,inheritance,C#,Inheritance,我试图重写/重载已在基类中重写的虚拟函数。为了更好地理解我想做什么,请看以下示例: public class Parent { public virtual void foo() { print("Parent::foo()"); } } public class Derived : Parent { public override void foo() { print("Derived::foo()"); } } public
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()?
是否可以重写派生的::foo()?如果不是,你会建议我如何解决这个问题?这将调用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()
如果没有看到您的调用代码,我不能肯定,但是您确定没有犯错误并创建了一个派生的实例吗?这在ideone上非常有效。您用来调用它的代码是什么?这应该行得通。@ja72其实不行,只是它会编译并运行。它确实通过工作代码证明了这在概念上是正确的。(OP的代码使用“打印”,无法编译…)