我可以为overriden方法调用base

Yur*_*riy 3 .net c# oop overriding

除了使用重构之外,是否可以从B类的实例调用方法AF().谢谢..


  class Program
  {
    public class A
    {
      public virtual void F()
      {
        Console.WriteLine( "A" );
      }
    }
    public class B : A
    {
      public override void F()
      {
        Console.WriteLine( "B" );
      }
    }

    static void Main( string[] args )
    {
      B b = new B();  

      //Here I need Invoke Method A.F() , but not overrode..      

      Console.ReadKey();
    }
  }
Run Code Online (Sandbox Code Playgroud)

Ste*_*ger 6

可以使用new关键字来获得相同(命名)方法的另一个定义.根据引用的类型,你叫A"第B的实现".

public class A
{
  public void F()
  {
    Console.WriteLine( "A" );
  }
}
public class B : A
{
  public new void F()
  {
    Console.WriteLine( "B" );
  }
}

static void Main( string[] args )
{
  B b = new B();  

  // write "B"
  b.F();

  // write "A"
  A a = b;
  a.F();
}
Run Code Online (Sandbox Code Playgroud)

如果您觉得这new不是正确的解决方案,您应该考虑使用专有名称编写两个方法.


通常,如果方法被正确覆盖,则无法从类外部调用基本实现.这是一个OO概念.你必须有另一种方法.有四种方法(我可以想到)来指定这种区分方法:

  • 用另一个名字写一个方法.
  • 编写一个具有相同名称但另一个签名(参数)的方法.它被称为重载.
  • 用相同的名称写一个新的方法定义(使用new关键字)它被称为隐藏.
  • 将它放在接口上并显式实现至少一个.(类似于new,但基于界面)