Commentary on a method that redefines and redefines simultaneously in C #?

Here is the script

     public class Connection
     {
         public virtual void close()
         {
           /*Some code */
         }
     }

    public interface IHttpRelay
    {

         void close();

    }

    public class HttpConnection: Connection,IHttpRelay
    {
         public /*keyword*/ void close()
         {
            base.close();
         }
    }

    public class Http:HttpConnection
    {
         public override void close()
         {
           /*Some code */
         }
    }

My question is to know if I should declare the close () method in the HttpConnection class with override or virtual , because it overrides and is overridden at the same time.

+5
source share
3 answers

You need to mark it override. If you mark it virtualin HttpConnection, it will hide the base class implementation, and not override it. As a result, it could not be used polymorphically. Mark one method virtual, the rest should simply be redefined.

As a simple example

class A
{
    public virtual void Frob()
    {
        Console.WriteLine("A");
    }
}

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

class C : B
{
    public override void Frob()
    {
        Console.WriteLine("C");
    }
}

B Frob, . . C A - "".

A obj = new C();
obj.Frob(); // "A" is written to the screen, not "C"

, , "A", , . , , . , ! , / . virtual override B, , , .

+2

. , .

+2

override. virtual :

virtual static, abstract, private override.

, virtual override : , - , , , virtual , .

+1

All Articles