"Go" interface in C # to implement polymorphism

Source: Internet
Author: User
Tags modifiers

The interface in C # implements polymorphism

We all know that virtual methods implement polymorphism, abstract methods to achieve polymorphism, and so on, we are today to see how to use the interface to achieve polymorphic

1. First we need to understand what is the interface, the consciousness of its existence

The interface is the one that exists to constrain the format of the method ( parameters and return value types ) .

the interface can implement multiple inheritance to compensate for the defects of single inheritance.

The interface can be regarded as a special abstract class, and the source code is seen by the anti-compilation .

the method in the interface does not have access modifiers because the CLR is automatically added and cannot have a method body

If a class implements an interface, it has to implement all the methods in that interface .

the interface should be used with caution to prevent contamination of the interface!

The interface represents only one capability, and the classes and interfaces that implement the interface do not have an inheritance relationship

The interface is for implementation, and the class is used for inheritance.

In fact, many times, seemingly can not interface, because the interface is a method of the Convention,

Indicates that you must have some method of this class, but do not write interfaces can also have these methods, using the interface,

You can use interface variables, unified invocation, to implement polymorphic

10. Only methods can be defined in an interface, and variables cannot be defined.

2. The difference between abstract classes and interfaces:

When there is a parent-child class relationship between the objects that you need, consider using an abstract class.

When there are no inheritance relationships between objects, only the same ability, consider using interfaces

3. Popular understanding of interfaces

The plane flies, the birds fly, they all inherit the same interface "Fly"; but F22 belongs to the abstract class of airplanes,

Pigeons belong to the abstract class of birds.

Just like the doors of iron doors are door (abstract class), you want a door I can't give (can't instantiate),

But I can give you a concrete iron gate or wooden door (polymorphic); and it can only be a door, you can't say it is a window (single inheritance);

A door can have a lock (interface) can also have a doorbell (multi-implementation).

The door (abstract class) defines what you are, and the interface (lock) specifies what you can do

(An interface is the best thing to do, you can't ask for a lock to make a sound (interface pollution))

Let's give an example of using an interface to achieve polymorphism:

01. Create a new Fly interface

 using   System;  using   System.Collections.Generic;  using   System.Linq;  using   System.Text;  using   System.Threading.Tasks;  namespace   interface { //  Fly interface  public  interface   IFly { //  The method in the interface does not have access modifiers because C   LR is automatically added and cannot have method body  void   Say (); }}

02. Create an Eating interface

 using   System;  using   System.Collections.Generic;  using   System.Linq;  using   System.Text;  using   System.Threading.Tasks;  namespace   interface { //  eating interface  public  interface   IEat { //  The method in the interface does not have access modifiers because C   LR is automatically added and cannot have method body  void   eat (); }}

03. Create a bird to implement the flying interface and the eating interface

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceInterface {//The Bird realizes the Flying interface and eats the interface     Public classGrid:ifly,ieat//Note interfaces: Interfaces are called inheritance, classes: Interfaces are called implementations    {        //if a class implements an interface, it has to implement all the methods in that interface .         Public voidSay () {Console.WriteLine ("The birds are flying ."); }         Public voidEat () {Console.WriteLine ("the bird is eating"); }    }}

04. Create an aircraft class to achieve the Flying interface

usingSystem;usingSystem.Collections.Generic;usingSystem.Globalization;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceInterface {//The plane realizes the flying interface    Public classPlan:ifly { Public voidSay () {Console.WriteLine ("The plane is flying ."); }    }}

05. In the Main method implementation call

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceInterface {classProgram {Static voidMain (string[] args) {            //defining an array of fly interfaces instantiation objectsifly[] Iflies =            {                NewGrid (),NewPlan ()}; //Loop Array call method to implement polymorphism            foreach(IFly IFlyinchiflies)            {Ifly.say (); }            //Bird Eating Instantiation ObjectIEat ieats =NewGrid (); //calling methods to implement polymorphismieats.eat ();        Console.ReadLine (); }    }}

This enables polymorphism and results in the following:

Note: If you have a class that implements two interfaces, it is unfortunate that the two interfaces (for example: Ifly,iplay) have the right two named methods (Eat)

We all know that.

If a class implements an interface, it has to implement all the methods in that interface.

What about this? The method of its own solution:

We can use the interface name. method to implement

  // implements the iFLY and iplay two interfaces, but there are eat methods   in all two interfaces  Public class Dog:ifly,iplay    {        // If a class implements an interface, it has to implement all the methods       in that interface // so that we can use the interface name. method to implement        void  ifly.eat ()        {                    }        void  iplay.eat ()        {                    }    }

4. Interface Summary (excerpt):

An interface is a protocol between components that describes the services that a component provides to the outside. Technically speaking, an interface is a set of data structures that contain a functional approach. With this set of data structures, the client code can invoke the functionality of the Component object. Interfaces can inherit from the parent interface. The inheritance of an interface is first of all descriptive inheritance, not implementation inheritance, and its implementation needs to be implemented by class or struct; Second, interface inheritance can be multiple inheritance.

The nature of the property is the method, and the essence of the indexer is the attribute.

The interface contains members that have methods, properties, index indicators, and events. Since the interface allows multiple inheritance, it can be avoided in a place where two of the semantics may occur. You can use classes to implement interfaces. The implementation of locating an interface member in a class is called an interface map. The class must provide a concrete implementation for all members of the interface, including members explicitly defined in the interface, and members that the interface inherits from the parent interface. Similarly, explicit interface member executions can be used to avoid generating two semantics in the implementation of an interface. Derived classes can be re-implemented on interfaces that the base class already implements.

An abstract class can also implement an interface, but an interface member must map to an abstract member of an abstract class. If the derived class of an abstract class is a non-abstract class, the interface member must be implemented through the method overload.

"Go" interface in C # to implement polymorphism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.