.net abstract override quirk

Suppose I have the following C # classes:

abstract class a
{
    protected abstract void SomeMethod();
}

abstract class b : a
{
    protected abstract override void SomeMethod();
}

class c : b
{
    protected override void SomeMethod()
    {

    }
}

Is there any point in overriding a method in b when it can be written just as easily:

abstract class b : a
{
}

What would be the “preferred” way to overlay b? And if it makes no sense to redefine an abstract method or property, why is this allowed?

+3
source share
5 answers

One of the reasons you might want to do this: it shows intent. It explains that yes, you know that this method is abstract in the base class. I know this, and I still want it to be abstract here.

, , , ( ).

, ... .

+5

. :

" , . , , .

" abstract "" override " # - . , , .

, : C B, B A. A Foo() Goo(). , " " . 1) , B Goo(), C Foo(). Foo() " ". , B , Foo() A, .

2) , B C Foo() A Foo(). B Foo() ( B , Foo() ) ( B C, ; , A ). . , A = TextReader, Foo = ReadLine, B = a , C = , ReadLine() (). TextReader ReadLine() Read(), . , Read(), ReadLine(). , B Read(), ReadLine(), ReadLine() " ", C ReadLine() TextReader.

," " , ; , . , . , ".

1:

public abstract class A
{
    public abstract void Foo();
    public abstract void Goo();
}

public abstract class B : A
{

    public abstract override void Foo();

    public override void Goo()
    {
        Console.WriteLine("Only wanted to implement goo");
    }
}

public class C : B
{

    public override void Foo()
    {
        Console.WriteLine("Only wanted to implement foo");
    }
}

2:

public abstract class A
{
    public virtual void Foo()
    {
        Console.WriteLine("A Foo");
    }
    public abstract void Goo();
}

public abstract class B : A
{

    public abstract override void Foo();

    public override void Goo()
    {
        Console.WriteLine("Only wanted to implement goo");
    }
}

public class C : B
{

    public override void Foo()
    {
        Console.WriteLine("Forced to implement foo");
    }
}

, , .

+2

, - :

  • .
  • , .
  • , , .
  • .
  • , .
+2

:

override , . , .

abstract class b : a
{
  [SomeAttribute]  
  protected abstract override void SomeMethod();
}
+2

You do not need to override SomeMethod () in b. An abstract class declares that it can have undefined / abstract methods. When you extend one abstract class to another, it implicitly inherits any abstract methods from the parent.

0
source

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


All Articles