开发者

C# Interfaces Question

I'm trying to understand interfaces.

From what I know about interfaces is that they are used along with classes and allows a class to be attached to an interface class? I don't quite understand the concept. When and why would I want to use this? I'm reading from a book it was to put behaviors into classes then by interfacing a common object can have multiple behaviors?

creating something like

    Vehicle myObject = new Vehicle();
    Interface1 something = myObject;
    something.someFunc();


Interface Interface1 {
   void someFunc();
}
开发者_如何学Python


An Interface is a contract of behaviour. It says "if you implement me, you must do these things". Any class implementing an Interface must meet that contract (i.e. provide a concrete implementation of everything specified in all interfaces) in order to even compile.

Seperating out behaviour from implementation is an example of re-use.

In C#, a class can implement many interfaces but only inherit from one class. Since C# doesn't support multiple inheritance (thankfully), interfaces are a way to produce something similiar.


You can think of an interface like a contract. A type implementing an interface must provide all methods defined in the interface. Also, other code can treat an instance of your type as an instance of the interface, without knowing the exact type. That can be useful for example for plugin architectures, where you load plugins at runtime and you really can't know in advance which type implements your interface. With interfaces, you can just define an interface IPlugin and look for types implementing it.


An interface is a way to guarantee that a particular behaviour will be present.

To elaborate on your example above

something.someFunc();

What you need at this point in your code, is that whatever be the object passed to you, it should have someFunc() method implemented.

In this case, you are passing a Vehicle.

Now, imagine that this code is inside a method and instead of

void function ThisMethodCallsSomeFunc (Interface1 myObject)
{   
    myobject.someFunc();
}

Now, in this method, i could pass a myObject of Vehicle (as long as Vehicle implements Interface1). However, additionally, imagine i have another class 'RavenousBugBlatter' and that implements Interface1 as well, i can instead pass that object to this ThisMethodCallsSomeFunc and have its someFunc called out as well.

Does that help clarify how interfaces help in this scenario ?


interface IFlyable
{
    void Fly();
}

class Bird : IFlyable
{
    public void Fly() { }
}

class Plane : IFlyable
{
    public void Fly() { }
}

List<IFlyable> things = GetBirdInstancesAndPlaneInstancesMixed();
foreach(IFlyable item in things)
{
   item.Fly();
}

Bird and Plane have no common base class except Object, but you can see using the same interface we can deal with them grouply in our program, because they have the same "feature": Fly.


I really like the way things are explained in the Ninject documention, so I'll just use their examples. You can always read the full documentation here: https://github.com/ninject/ninject/wiki/_pages

Let's say you have a Sword class like this:

class Sword
{
  public void Hit(string target)
  {
    Console.WriteLine("Chopped {0} clean in half", target);
  }
}

The sword can hit something. Now suppose you have a Samurai class. This Samurai class uses a Sword to attack.

class Samurai
{
  private Sword _sword;

  public Samurai()
  {
    _sword = new Sword();
  }

  public void Attack(string target)
  {
    _sword.Hit(target);
  }
}

This all works nice and fine like this:

class Program
{
  public static void Main()
  {
    Samurai warrior = new Samurai();
    warrior.Attack("the evildoers");
  }
}

You now have a Samurai class that is tightly coupled to the Sword class. What when you want to have an army of Samurai? Some use a Sword, some use BowAndArrow and some use a Shuriken. You would have to modify your Samurai class each time you add a new weapon. Because that's what a Sword, a BowAndArrow and a Shuriken are. They are all weapons that the Samurai can use to Hit something.

This is where interfaces come in play. Let's abstract out the functionality of attacking with a weapon using an interface:

interface IWeapon
{
  void Hit(string target);
}

class Sword : IWeapon
{
  public void Hit(string target)
  {
    Console.WriteLine("Chopped {0} clean in half", target);
  }
}

class BowAndArrow : IWeapon
{
  public void Hit(string target)
  {
    Console.WriteLine("Shot {0} right in the chest!", target);
  }
}

class Shuriken : IWeapon
{
  public void Hit(string target)
  {
    Console.WriteLine("Pierced {0}'s armor", target);
  }
}

What we have now is an interface IWeapon and three classes implementing that interface. The interface acts like a contract. It says "If you implement me, you must provide the Hit method. That methods should accept a string parameter and shouldn't return anything".

What does that change for our Samurai? Instead of being coupled to class Sword, it can now use the interface IWeapon like this:

class Samurai 
{
  private IWeapon _weapon;

  public Samurai(IWeapon weapon)
  {
    _weapon = weapon;
  }

  public void Attack(string target)
  {
    _weapon.Hit(target);
  }
}

Now the Samurai class uses an IWeapon. Because each class implementing the IWeapon interface agrees to the contract of providing the Hit method, the Samurai class doesn't need to know or care what weapon it is wielding. It just knows that it has a weapon and it can Hit with is.

Like this:

class Program
{
  public static void Main()
  {
    Samurai warrior1 = new Samurai(new Sword());
    Samurai warrior2 = new Samurai(new Shuriken());
    Samurai warrior3 = new Samurai(new BowAndArrow());

    warrior1.Attack("the evildoers");
    warrior2.Attack("the big guy in front");
    warrior3.Attack("the scared guy running away");
  }
}

I hope this makes some sense.


Think of an interface as a definition of what your class should contain, you define this skeleton then you apply it to a class, this class then HAS to define those functions from the interface.

MyClass : IMyInterface

This is useful for polymorphic functionality when you may have similar objects which implement the same functions but the code inside them is different.


Let's make a very simple example where you would need an Interface:

Let's say you are programming a library to draw objects on the screen. For that purpose, you might have a number of Objects that can be drawn, for example:

class Cube {
 void draw(//Draw a cube);
}

Now let's say there's something that tells those Objects to draw themselves. If there's only some cubes, it's easy: "All Cubes: Draw yourselves on the screen"

But now you will want to have different type of Object! Here's where an Interface comes into play:

interface DrawableObject {
 void draw();
}

and

class Cube:DrawableObject {
 void draw(//Draw the Cube);
}

class Triangle:DrawableObject {
 void draw(//Draw the Cube);
}

class Circle:DrawableObject {
 void draw(//Draw the Cube);
}

Now you can do: "All DrawableObjects: Draw yourselves on the screen"! Because Circle,Cube and Triangle all implement DrawableObject, they are all bound to have the "draw" Method.


As say @Mitch Weat, Interface is a contract who imposes to implement code for a method signature.

Try to see interfaces like a mask, you can look a class through this mask without asking if the class will be able to do that.. If the class implement the interface the class will be able to do all methods the interface describe!


Interfaces define a set of properties and methods that implementing classes must have. The main use of interfaces is that implementing classes can be passed around as any of the interfaces they implement, and this can simplify and future-proof your code.

Let's say you wanted to create a method that adds together all the numbers in a collection. Without interfaces, you'd have to cater to every kind of collection there is: ArrayList, List, Queue, Stack, int[], LinkedList, and so on and so on. (There are many, many more). However, all these classes have common behaviour that is defined by their interfaces, such as adding, removing, and iterating. In this case, all you really need is the ability to traverse the collection, so your method can look like this:

public static int Sum(IEnumerable listOfInts)
{
    int total = 0;

    foreach (object obj in listOfInts)
    {
        if (obj is int)
            total += (int)obj;
    }

    return total;
}

Now you can pass in any object so long as it implements IEnumerable, which all collections do.

int total = Sum(new int[] { 3, 51, -2, 4 });

Or:

ArrayList list = new ArrayList();

list.Add(4);
list.Add(52);
...
int total = Sum(list);


One way in which interfaces can be useful in a real-world business sense would be if you were to allow 3rd party developers to develop plugins for your application.

So for example, lets take a point of sale application. This application will work with a set number of peripherals - eg a Symbol LS2208 barcode scanner, Avery-Berkel Scales etc. Each device operates and communicates with the software in different ways, but your POS software only knows a few set commands - eg with a barcode scanner: ReadCode() IsCodeValid() Initialise() etc.

The implementation beneath that could be anything, but your POS software only cares about those few methods. So you would define an interface called IBarcodeScanner, which declares those few method stubs.

Your 3rd party developer wants to then add support for a Symbol LS4015 scanner for example, which communicates differently. They write their own driver for it, and then write those few methods defined in your interface to expose all the functionality. Your POS software can then call just those 4 methods and be guaranteed that it will work - it doesn't have to care about all the customisation done by that developer, it just uses the methods that it knows about. Makes life a lot easier in larger scale developments.


The key feature of interfaces is to allow classes that potentially derive from different object hierarchies to be treated the same Polymorphically

eg

public interface IDoSomething
{
    string DoIt();
}

public class ClassOne : TextBox, IDoSomething
{
    public string DoIt()
    {
        return "OK from a textbox";
    }
}

public class ClassTwo : Panel, IDoSomething
{
    public string DoIt()
    {
        return "OK from a panel";
    }
}

and then you can use them polymorphically

List<IDoSomething> items = GetMyItems();
foreach (var item in items)
{
    Console.WriteLine(item.DoIt());
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜