无法覆盖虚拟C#方法

问题描述 投票:0回答:4

我有以下代码

public interface IFoo
{
    void Bar();
}
public class Parent : IFoo
{
    public virtual void Bar(){}
}
public class Child : Parent, IFoo
{

    public override void Bar(){}

}

IFoo test = new Child();
test.Bar(); 

test.Bar()总是调用父方法

任何帮助将不胜感激

c# inheritance interface overriding virtual
4个回答
1
投票

只有在明确实现后才应该发生。

我刚刚测试过,它可以工作。


1
投票

代码正确。

public interface IFoo
{
    string Bar();
}
public class Parent : IFoo
{
    public virtual string Bar() 
    {
        return "Hello world";
    }
}
public class Child : Parent, IFoo
{

    public override string Bar() 
    {
        return "Hello world after override";
    }
}
static void Main(string[] args)
{
    IFoo test = new Child();
    Console.WriteLine(test.Bar());

    Console.ReadLine();
}

输出为:

Hello world after override

0
投票

WorksForMe:问题一定在其他地方,当我运行此代码时,我看到正确地调用了子方法。要编译您的代码,我必须从接口中的方法中删除“ public”,然后给两个Bar()方法赋予一个主体。


0
投票

C#4.0说语法有错误

public interface IFoo
{
    void Bar();
}
  • 访问修饰符在这里无效因此,如果删除“ public”,代码将按照您的计划使用方法的子版本运行]
© www.soinside.com 2019 - 2024. All rights reserved.