【问题标题】:Unable to override virtual c# method无法覆盖虚拟 C# 方法
【发布时间】:2011-05-21 05:32:12
【问题描述】:

我有以下代码

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() 总是调用父方法

任何帮助将不胜感激

【问题讨论】:

  • 您发布的代码无法编译:IFoo.Bar 中不能有 public 修饰符。因此,我们无法判断您的代码有什么问题。请张贴真正的代码剥离到你的问题的核心。很可能您在Parent 中显式实现IFoo.Bar,因此Child 不会覆盖它。
  • 您将不得不提供更多代码。该测试导致Child.Bar 在这里运行。 (而且您的接口定义在语法上不正确——接口成员没有可见性说明符。)
  • 您的示例无法编译。你的意思是让 Parent 成为一个抽象类吗?
  • 你的代码工作正常,它调用了子方法。

标签: c# inheritance interface overriding virtual


【解决方案1】:

只有当你明确地实现它时才会发生这种情况。

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

【讨论】:

    【解决方案2】:

    代码是正确的。

    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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        C# 4.0 说你有语法错误

        public interface IFoo
        {
            void Bar();
        }
        
        • 访问修饰符在此处无效 因此,如果删除“public”,代码将按照您的计划使用子版本的方法运行

        【讨论】:

        • 如果它不编译,它根本不会运行。因此,这不可能是真正的问题。我怀疑 OP 发布了与真实代码相似的伪造代码,但还不够接近我们来诊断实际问题。 (而且这个伪造的代码有语法错误;大概真实的代码没有。)
        • 是的,但是在这种情况下 - 这是一个正确的解决方案 - 接口声明中的语法错误,因为在所有其他情况下“覆盖”将覆盖基本方法
        猜你喜欢
        • 2013-01-15
        • 2018-01-28
        • 1970-01-01
        • 1970-01-01
        • 2012-06-19
        • 2012-02-19
        • 2012-10-26
        • 2014-03-18
        • 1970-01-01
        相关资源
        最近更新 更多