What practical use of the interface is not implemented directly in the class?

I think I have a very naive question that I did not know before that this was possible. Forgive me if my title question is a bit vague because I don’t even know how to describe it. Here is the code that looks weird to me.

public interface IMyInterface
{
    void ImplementMe();
}

public class StandAlone
{
    public void ImplementMe()
    {
        Console.writeline("It works!");
    }
}

public class SubClass : StandAlone, IMyInterface
{
    // no need to implement IMyInterface here but it still work!!!
}

IMyInterface myInterface = new SubClass();
myInterface.ImplementMe();   // Output : "It works!"

I just want to know the following:

  • What is the correct term to describe this approach?
  • What are the practical benefits of this approach?
  • What problem is he trying to solve? or Which scenario is applicable?
+4
source share
4 answers

, , - StandAlone, , StandAlone. . ( , , ), StandAlone . , :

public class SUT
{
    private readonly StandAlone dependency;

    public SUT(StandAlone dependency)
    {
        this.dependency = dependency;
    }

    // ...
}

, IMyInterface StandAlone. SubClass .

public class SUT
{
    private readonly IMyInterface dependency;

    public SUT(IMyInterface dependency)
    {
        this.dependency = dependency;
    }

    // ...
}
+6

SubClass IMyInterface - . , .

, , ( , ).

- . , :

class SubClass : BaseClass, IInterface
{
  void IInterface.MyMethod()
  {
    base.MyMethod();
  }
}

, , , :

  • , , .
  • , , , .
  • inferface , BaseClass.

, , .

: ? - ( , ). - . .

+3

( ) , Standalone ( ) , IMyInterface .

:

  • . ImplementMe.
  • Standalone ThirdParty.dll (, )
  • Standalone .
  • , ImplementMe, onw, . (public class MyOwnImplemetation : IMyInterface {... })

DI Standalone MyOwnImplemetation, IMyInterface.

+2

.

, , :

public class Person 
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
}

, - , , .

, , , , , .

, :

public interface ICanBeUniquelyIdentifiable
{
     Guid Id { get; set; }
}

... and we do not sell it on Person, but do it on Employee:

// Now an employee is an actual object that can be uniquely identifiable,
// and this isn't true because Person has an Id property, but because
// Employee fulfills the contract!
public class Employee : Person, ICanBeUniquelyIdentifiable
{
}

Background

I would say that your reasoning should be that you implement interfaces, where they really matter for implementation , and reuse should not be a key point in implementing interfaces.

In fact, you have to implement interfaces for objects that must be accepted on some kind of API, and you just need a subset of the full type of this object.

0
source

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


All Articles