Implementing polymorphism in C #, what's the best way to do this?

The first question is here, so hopefully you all go softly at me!

In the last few days, I read a lot about polymorphism and try to apply it to what I am doing in C #, and it seems that there are several different ways to implement it. Hopefully I have dealt with this, but I would have been delighted even if I hadn’t explained.

From what I see, I have 3 options:

  • I can simply inherit from the base of the class and use the ' virtual' keyword for any methods that I want my derived classes to override.
  • I could implement an abstract class with virtual methods and do it this way
  • Could I use the interface?

From what I see, if I do not require any implementation logic in the database, then the interface gives me great flexibility (since I then do not limit myself in relation to multiple inheritance, etc.), but if I require that the base could do something on top of what the derived classes did, and that 1 or 2 would be the best solution?

Thanks for any contribution to these guys - I read so much this weekend, both on this site and elsewhere, and I think I understand the approaches right now, but I just want to clarify the language in a certain way if I'm on the right way. I hope I also noted this correctly.

Cheers, Terry

+3
source share
6 answers

; - (, ).

virtual ; ...

, , :

public interface IFoo {
    void Bar();
}
class Foo : IFoo {
    public virtual void Bar() {...}
}
class Foo2 : Foo {
    public override ...
} 

abstract - ; abstract : ? , abstract.

, , , ; - , interface ( ):

public interface IFoo {
    void Bar();
}
public static class FooExtensions {
    // just a silly example...
    public static bool TryBar(this IFoo foo) {
        try {
             foo.Bar();
             return true;
        } catch {
             return false;
        }
    }
}
+6

. , "". .

, , , . , , , .

+2

:

  • , .
  • ( , ., , Windows Forms, , , ..
  • .

, , ( ), , - .

public interface IFoo
{
    void Bar();
    enter code here
}

public abstract class BaseFoo : IFoo
{
    void Bar
  {
        // Default implementation
  }
}

public class SomeFoo : BaseFoo
{

}

- , .

, :

public class Bar
{
   int DoSometingWithFoo(IFoo foo)
{

    foo.Bar();
}
}

, .

+2

, : " ?", - , . , , .

, , , , , , , ...

+1
+1

, .

, .

, , , , , .

, , , .

.

, , , (, 1 ).

, .

In any case, it’s best to keep the classes simple, along with their inheritance, because the more complex they become, the greater the likelihood of errors.

0
source

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


All Articles