Can I call the base to override the method

Is it possible to call the AF () method from an instance of class B, with the exception of using refactoring. Thank..


  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();
    }
  }
+3
source share
5 answers

You can use the keyword newto have a different definition for the same (named) method. Depending on the type of link, you call Aimplementations 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();
}

If you think this is newnot the right solution, you should consider writing two methods with a distinguished name.


, , . . . ( ) :

  • .
  • , (). .
  • ( new). hiding.
  • . ( new, )
+6

base.F();

+3

base.method() .

+1

. , , . , ( , @Edward Leno mentiods).

class Program 
  { 
    public class A 
    { 
      public virtual void F(bool useBase) 
      { 
        Console.WriteLine( "A" ); 
      } 
    } 
    public class B : A 
    { 
      public override void F(bool useBase) 
      { 
        if(useBase) base.F();
        else Console.WriteLine( "B" ); 
      } 
    } 


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

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

        Console.ReadKey(); 
        } 
    }
  }
+1

, ( , , ). , B? , :

public void F (int i)
{
    base.F();
}

, :

b.F(1);
0

Source: https://habr.com/ru/post/1761916/


All Articles