开发者

Can someone explain the exact use of interfaces in C#?

开发者 https://www.devze.com 2022-12-29 17:06 出处:网络
Can someone explain th开发者_运维知识库e exact use of interfaces in C#?Has msdn not been helpful on this?

Can someone explain th开发者_运维知识库e exact use of interfaces in C#?


Has msdn not been helpful on this?

http://msdn.microsoft.com/en-us/library/87d83y5b.aspx


This has been discussed so many times here in the past that it is hard to pick any one duplicate for this question.

To save the time of repeating what has been said before, try this search, and start going through the results.


Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:

interface IVehicle
{
   Engine vehicleEngine { get; set; }

   bool StartEngine();
}

Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:

public Car : IVehicle
{
   // MUST implement vehicleEngine and StartEngine:

   public Engine vehicleEngine { get; set; }

   public bool StartEngine()
   {
       // Cars needs to do xyz to start
   }

   public int MaxNumberOfPassenger { get; set; } // Specific to Car
}

and then:

public Truck : IVehicle
{
   // MUST implement vehicleEngine and StartEngine:

   public Engine vehicleEngine { get; set; }

   public bool StartEngine()
   {
       // Trucks needs to do abc to start
   }

   public int MaximumLoad { get; set; } // Specific to Truck
}

This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.


In the most simple terms, an Interface expresses what one, or more classes can do, although the implimentation may vary across the various classes.


Polymorphism You can use 2 classes that implement the same interface without having to know exactly which concrete class it is. It aids in keeping code loosely coupled.


An interface defines the minimum requirements that a class that can be instantiated must implement. It expresses this through methods.

For instance, an interface could define a function called Foo which takes an integer and returns a boolean:

public interface ICanFoo
{
    bool Foo(int number);
}

Any class which implements this interface must also implement this method:

public class Fooable : ICanFoo
{
    public bool Foo(int number)
    {
        // do something
    }
}

The implementation within the method is up to the specific classes which are implementing the interface.

By using interfaces you no longer care about implementation are compile time, but rather specification. You can call it like this:

ICanFoo myFooable = ...
bool success = fooable.Foo(4);

The actual type of fooable can be any class that implements ICanFoo since you know that ICanFoo will always define a method implementation for the Foo method.

0

精彩评论

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

关注公众号