开发者

Significance of Interfaces C#

开发者 https://www.devze.com 2022-12-20 00:14 出处:网络
I would like to know the significant use of Interface. I have read many articles but not getting clearly the concept of interface.

I would like to know the significant use of Interface. I have read many articles but not getting clearly the concept of interface.

I have written a small program. I have defined the Interface Itest.Class(Manager) has implemented the Interface.Another class(Employee) has not implemented interface. But defined the same method(DoSomething()) in the interface in the class(Employee). 开发者_如何学运维I can call the method from the class object. Then why should i go and implement interface. I can directly implement the method in a class and call the method. Why should i go for extra step of implementing method in a Interface and then inheriting the interface by class. I know interface supports multiple inheritance, but I am not using multiple inheritance in this example.

Thanks for any ideas or input.

public interface Itest
{
    void DoSomething();
}

public class Manager:Itest
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }

}
class Employee
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Manager m = new Manager();
        m.DoSomething();
        Employee e = new Employee();
        e.DoSomething();
        Console.ReadLine();
    }
}


Interfaces allow you to sort of use multiple inheritance. In your example, it woulda allow you to put an instance of Employee or Manager into the same variable, and then call DoSomething on that variable, with the method call being dispatched to the instance that is currently referenced by that variable. For example:

public interface IEmployee {
    void DoSomething();
}
// assume Manager and Employee both implement IEmployee

IEmployee ie = new Manager();
ie.DoSomething();    // calls Manager.DoSomething()
ie = new Employee();
ie.DoSomething();    // calls Employee.DoSomething()

If you didn't use interfaces, you would have to do:

object o;

// assign Manager or Employee (or something else!) to o

if (o is Manager)
    ((Manager)o).DoSomething();
else if (o is Employee)
    ((Employee)o).DoSomething();

An interface defines a contract, and as long as an instance implements that interface you don't care what it actually is at runtime. You can have the same class implement multiple interfaces, and then use instances of that class in all variables of those interfaces. You couldn't use the same for abstract classes, as a class can only inherit off one class at a time.

One example where I'm using interfaces now is to define an object model - I've got interfaces for various properties (IHasStorage, IHasPrivileges, IHasCheezburger), then the classes representing the concrete objects implement whichever and however many interfaces are appropriate for that class' properties


Interfaces are used for abstraction (abstract classes are also used for this, but normally contain some implementation that is intended for reuse).

In C# they allow the use of multiple inheritance, meaning you can implement many different interfaces in one class.

If you have many different implementations of an interface, you can substitute them for one another, so long as you use the interface declaration.

For example:

IAnimal can be implemented by Cat and by Dog. In other code, you want to call the Talk method that is declared in the interface. Your code does not have to care whether it is a Cat object or a Dog object. You can add a Duck or a Human and not change that piece of code.

This is also useful when testing your code with mock objects, so a simple object can be substituted for the real one for testing purposes.

Some interfaces are used as markers so reflection can pick them up easily (on example is the ISerializable interface, marking a class as serializable).


Implementation inheritance models an "IS A KIND OF" relationship, whilst interface inheritance models a "CAN BEHAVE LIKE" relationship. It's no coincidence that many of the BCL interface names end with "-able", representing the ability to do something. To demonstrate, image the following code:

class Person
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
}

class Employee : Person
{
  public int Id{get;private set;}
}

Clearly, an Employee "is a kind of" Person. All employees are people, therefore they all have a Name and can Walk(). By all means make Person or Employee abstract, it doesn't change the fact that all employees are people.

Now let's get a bit more abstract and talk about the concept of being a vehicle. The absolute essential for a thing to be a vehicle is that it must be able to move and stop. You might include steering and carrying passengers but I'm keeping it very abstract.

Let's think about some things that are vehicles. A car, of course, but how about a person? They can move and stop (and when I give my nephews and nieces piggy-backs I'm carrying passengers too!) A wheely chair? I'm forever davrossing around the office. I'm a keen sailor too, and use the wind to accelerate and decelerate my vehicle.

You can't model this kind of a relationship using implementation inheritance, because you have lots of different things that "can act like" a vehicle but don't neccessarily inherit from the same base class.

A pogostick (with apologies to professional pogo-ers) IS A KIND OF Toy, but CAN ACT AS a vehicle. Not all toys are vehicles. A Person has no relationship to a Car, other than the fact that it CAN ACT AS a vehicle.

interface IVehicle
{
  void Move();
  void Stop();
}

class Toy{}

class PogoStick : Toy, IVehicle
{
  public void Move(){ /* boing boing */}
  public void Stop(){ /* fall over */}
}

class Car: IVehicle
{
  public void Move(){ /* vroom vroom */}
  public void Stop(){ /* <screeeech!> */}
}

class Person : IVehicle
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
  void IVehicle.Move() { Walk(); }
  void IVehicle.Stop() { /*whatever!*/}
}

class Program
{
  static void Main()
  {
    IVehicle[] vehicles = new IVehicle[3];
    vehicles[0] = new PogoStick();
    vehicles[1] = new Car();
    vehicles[2] = new Employee(); //implements IVehicle because it IS A KIND OF Person

    vehicles.ForEach(v => v.Move());

    //it's worth pointing out that
    vehicles[2].Stop();
    //works fine, but
    Person p = new Person();
    p.Move();
    //won't, as I explicitly implemented the interface, meaning I can only get at the
    //methods via a reference to the interface, not to the implementing class.
  }
}

To use an example from .NET itself, what on Earth does a string have in common with a List? Not a lot, except that I can "foreach" both of them:

class Demo
{
  static void Main()
  {
    string s = "Hello!";
    List<Employee> payroll = new List<Employee>();

    for each (var item in s)
    {
      Console.WriteLine(item);
    }

    for each (var item in payroll)
    {
      Console.WriteLine(item);
    }
}

The common base class for string and List is object, but not all objects are "for-each-able", so there has to be something else going on. Namely that they both implement the IEnumerable interface (there's that -able!)


When you add the interface to Employee the two classes become compatible through that interface:

public class Manager:Itest { ... }

class Employee:Itest { ... }

static void ShowSomething(Itest test)
{
   test.DoSomething();
}

static void Main(string[] args)
{

    Manager m = new Manager();            
    Employee e = new Employee();

    ShowSomething(m);
    ShowSomething(e);
}

Take a look at how the BCL uses interface, to get started look up IDisposable, ISerializable, IComprable and IEnumerable


The inheritance of interface give you the possibility to change your implementation with other class or object without breaking your code. The Interface means that you make a contract with the clients of your code that you will provide some functionality and they don't have to know which particular class to call for this. The Interface adds a layer of abstraction, so your the clients of your code will not depend on how your implement the solution. They just know that you will provide them, what is in the interface.


interfaces are useful in a bit more complex scenarios, e.g.

(1) You need multiple inheritance (in c# you can't inherit from 2 classes), e.g. you have interfaces IProduct, IDisposable. Not every product needs to be disposed, so it doesn't make sense to implement it on all products, etc.

(2) When you use dependency injection (inversion of control) and a mocking framework (e.g. RhinoMocks) for you unit testing - then you have to work with interfaces, otherwise your mocking framework is not going to work.


You know, funny enough that I was just talking to one of our developers at work about this very topic today.

The easiest way for me to explain what an interface and it's usability is, is the following example.

interface IGraphicsRenderer
{
     Render(List<Triangle> triangles);
}

Then you might have 2 types of rendering engines, Direct3D or OpenGL

class Direct3DRenderer : IGraphicsRenderer
{
   public void Render(List<Triangle> triangles);
}

class OpenGLRenderer: IGraphicsRenderer
{
   public void Render(List<Triangle> triangles);
}

To show it's usefulness, you might have something along the lines of

IGraphicsRenderer renderer = new Direct3DRenderer();
renderer.Render(foo);

to change the renderer, all you need to do is change the initialization.

IGraphicsRenderer renderer = new OpenGLRenderer();


A very good analogy for interfaces is provided Matthew Cochran

  • Why Use Interfaces?

"This make for a much easier "code world" in which to navigate. Imagine if instead of learning how to drive a car and then being able to drive any car, we had to learn how to drive each instance of every car we get into. It would be really inefficient if after learning how to drive the Ford Pinto we had to start all over again in order to figure out the Mustang. A much more efficient way is to deal with the cars interface: the steering wheel, turn signals, gas pedal and brake. This way, no matter what is implemented on the backend of the interface, we don't really care because in the end it subscribes to the basic car contract and that is how we will deal with it (through the interface).2

Along with the general explanation above, most of the modern Software Design pattern, very much rely on interfaces such as Dependendency Injection

  • Control Containers and the Dependency Injection by Martin Fowler

Consider this example:

You have a class that is capable of playing media files(mp3). You give that class to you friend who tries to play MPEG type of files. It would not be possible for him to do so without making significant changes to you class.

public class MusicPlayer 
    {
       void Play(Mp3 _mp3File){}
    }

consider this

Instead of passing type of mp3 file to Play Method what if you pass this Method, a derived from an interface of Type MediaType.

    public interface MediaType { }

    public class Mp3 : MediaType
    { }

    public class MPEG : MediaType
    { }

and class:

    public class MusicPlayer 
    {
       void Play(MediaType _mediaFile){}
    }

In this scenario, you can derive another MediaFile type and from MediaType like MPEG and pass that to the Play Method and it will happily accept it and play it for you(provided logic).

   public class TestPlayers
    {
        public void PlayMedia()
        {
            MusicPlayer musicPlayer = new MusicPlayer();
            musicPlayer.Play(new Mp3());
            musicPlayer.Play(new MPEG());
        }       
    }

Hope this helps


When You have too many class which drive from an Interface classyou ensure that all of them implement a Method.

Then if your Interface changes (e.g:

       public Interface IAnimal
            {
                public void Talk();
                public void Eat();
            }

and then you add another method

       public Interface IAnimal
            {
                public void Talk();
                public void Sleep();
                public void Eat();
            }

then you can ensure which all of them will implement the Sleep() method. if you have too many classes which dervice from IAnimal Inteface then youhave to implement Sleep() for all of them. this help you extend as easy as possible your derived classes


Of course you can implement the method declared in the interface without implementing the interface. Simple put, interfaces just make sure you don't forget about it (they will give you compile errors if any of the interface members in not implemented).


I assume you want a very simple answer.

There are 2 types of inheritance:

  • TYPE 1: interface inheritance (in simple terms: when the outside of the class is inherited)
  • TYPE 2: implementation inheritance (when the inside of the class is inherited)

If you write

class MyClass : Base {}

you are using BOTH type 1 and 2. But if you implement an interface that's clear type 1.

Type 1 is for polymorphic use and type 2 is for code reuse.

So the bottom line is if you want to use polymorphism but you

  • don't want to provide any implementation
  • or simply can't do it. Mostly in case of multiple inheritance - note: c++ allows it, it follows another philosophy

interfaces are for you :)

There are another uses(e.g. force the implementation of a method) but in my opinion this is the point.


Interfaces are for designs. The actual implementation follows what is defined in the design (read interface). The concept of interface gives one the flexibility to design a system without going into the details of the implementation, or keeping the design extensible by implementing the interfaces in the future. This is also known as abstraction.

While interface gives flexibility at the time of designing, it puts the constraint at the time of implementation. Any implementation of an interface need to be complete, means one need to implement all the specifications defined in the interface at the time of implementation. Also the other flexibility at this time is that one can implement multiple interfaces in one class.

This is a very strong concept that provides a very high degree of flexibility at the time of design and making sure that the implementation will not break the design.

0

精彩评论

暂无评论...
验证码 换一张
取 消