Basic _ C # Interface

Source: Internet
Author: User
C # Interface

Interface is usedInterfaceKeyword. For example:

interface IComparable  {      int CompareTo(object obj);  }  

The interface description can belong to anyClassOrStructure. An interface can be composed of methods, properties, events, indexers, or any combination of the four member types.The interface cannot contain fields.. The interface member must bePublic).

The class and structure can be inherited from the interface like the base class or structure of the class, but there are two exceptions:

  • Class or structureInherit multiple interfaces.

  • When the class or structure inherits the interface, itInherited member DefinitionsBut does not inherit the implementation.

To implement interface members, corresponding members in the classMust be public,Non-staticAnd hasSame nameAnd signature.

The class attributes and indexer can define additional accessors for the attributes or indexer defined on the interface. For example, an interface can declare an attribute with get accessors, and the class implementing this interface can declare the same attribute with get and set accessors at the same time. However, if the attribute or indexer is explicitly implemented, the accessors must match.

Interfaces and interface members are abstract; interfaces do not provide default implementations.

Interfaces can inherit from other interfaces. Class can inherit an interface multiple times through its inherited base class or interface. In this case, if you declare this interface as part of a new class,The class can only implement this interface once. If the inherited interface is not declared as a part of the new class, its implementation will be provided by the base class that declares it. The base class can use virtual members to implement interface members. In this case, the class inheriting interfaces can modify interface behavior by overwriting virtual members. For more information about virtual members, see polymorphism.

{
Expandcollapse (sectiontoggle0)
} "Onkeypress =" function onkeypress ()
{
Expandcollapse_checkkey (sectiontoggle0)
} "> Interface Overview

The interface can beNamespaceOrClassMember

The interface has the following attributes:

  • An interface is similar to an abstract base class: any non-Abstract type that inherits an interface must implement all the members of the interface.

  • The interface cannot be instantiated directly.

  • Interfaces can contain events, indexers, methods, and attributes.

  • The interface does not contain the implementation of methods.

  • Classes and structures can be inherited from multiple interfaces.

  • The interface itself can be inherited from multiple interfaces

Explicit interface implementation

If the class implements two interfaces and these two interfaces contain members with the same signature, implementing this member in the class will result in both interfaces using this member as their implementation. For example:

interface IControl{    void Paint();}interface ISurface{    void Paint();}class SampleClass : IControl, ISurface{    // Both ISurface.Paint and IControl.Paint call this method.    public void Paint()    {    }}

However, if two interface members execute different functions, this may result in incorrect implementation of one of the interfaces or incorrect implementation of both interfaces. You can explicitly implement interface Members-that is, create a class member that is called only through this interface and is specific to this interface. This is usedInterface NameAnd onePeriodName thisClass Member. For example:

public class SampleClass : IControl, ISurface{    void IControl.Paint()    {        System.Console.WriteLine("IControl.Paint");    }    void ISurface.Paint()    {        System.Console.WriteLine("ISurface.Paint");    }}

Class member iControl. Paint can only be used through the iControl interface, and isurface. Paint can only be used through isurface. Both methods are implemented separately.It cannot be used directly in a class/class instance.. For example:

SampleClass obj = new SampleClass();//obj.Paint();  // Compiler error.IControl c = (IControl)obj;c.Paint();  // Calls IControl.Paint on SampleClass.ISurface s = (ISurface)obj;s.Paint(); // Calls ISurface.Paint on SampleClass.

Explicit implementation is also used to resolve the situation where two interfaces declare different members with the same name (such as attributes and methods:

interface ILeft{      int P { get;}  }  interface IRight{      int P();  }  

To implement both interfaces at the same time, the class must use explicit implementation for Attribute P and/or Method P to avoid compiler errors. For example:

class Middle : ILeft, IRight  {      public int P() { return 0; }      int ILeft.P { get { return 0; } }  }

Interface Properties

public interface ISampleInterface{    // Property declaration:    string Name    {        get;        set;    }}

Interface Indexer

// Indexer on an interface:public interface ISomeInterface{    // Indexer declaration:    int this[int index]    {        get;        set;    }}// Implementing the interface.class IndexerClass : ISomeInterface{    private int[] arr = new int[100];    public int this[int index]   // indexer declaration    {        get        {            // Check the index limits.            if (index < 0 || index >= 100)            {                return 0;            }            else            {                return arr[index];            }        }        set        {            if (!(index < 0 || index >= 100))            {                arr[index] = value;            }        }    }}

Declare an event in the interface, and then implement the event in the class

public delegate void TestDelegate();   // delegate declarationpublic interface ITestInterface{    event TestDelegate TestEvent;    void FireAway();}public class TestClass : ITestInterface{    public event TestDelegate TestEvent;    public void FireAway()    {        if (TestEvent != null)        {            TestEvent();        }    }}public class MainClass{    static private void F()    {        System.Console.WriteLine("This is called when the event fires.");    }    static void Main()    {        ITestInterface i = new TestClass();        i.TestEvent += new TestDelegate(F);        i.FireAway();    }}
Explicitly implemented interface member
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_csref/html/514cde76-f981-474e-8b40-9493619f899c.htm
Implement interface members explicitly using inheritance
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_csref/html/8b402ddc-dff9-4869-89cb-d718c764e68e.htm
 

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.