Specification | interface
An interface defines a contract. A class or struct that implements an interface must comply with its contract. Interfaces can contain methods, properties, indexers, and events as members.
Example
Interface Iexample
{
String This[int index] {get; set;}
Event EventHandler E;
void F (int value);
String P {get; set;}
}
public delegate void EventHandler (object sender, EventArgs e);
Shows an interface that contains indexers, event E, Method F, and property P.
Interfaces can use multiple inheritance. In the following example,
Interface IControl
{
void Paint ();
}
Interface Itextbox:icontrol
{
void SetText (string text);
}
Interface Ilistbox:icontrol
{
void Setitems (string[] items);
}
Interface Icombobox:itextbox, IListBox {}
Interface IComboBox inherit from ITextBox and IListBox at the same time.
Classes and structs can implement multiple interfaces. In the following example,
Interface IDataBound
{
void Bind (Binder b);
}
public class Editbox:control, IControl, IDataBound
{
public void Paint () {...}
public void Bind (Binder b) {...}
}
Class EditBox is derived from class control and implements both IControl and IDataBound.
In the previous example, the Paint method in the IControl interface and the Bind method in the IDataBound interface were implemented using public members of the EditBox class. C # provides another way to implement these methods so that the implementation class avoids setting these members public. This is: interface members can be implemented with qualified names. For example, the Paint method is named IControl.Paint in the EditBox class, and the Bind method is named the IDataBound.Bind method.
public class Editbox:icontrol, IDataBound
{
void IControl.Paint () {...}
void IDataBound.Bind (Binder b) {...}
}
An interface member implemented in this manner is called an explicit interface member because each member explicitly specifies the interface member to implement. Explicit interface members can only be invoked through an interface. For example, the Paint method implemented in EditBox can only be invoked by casting to the IControl interface.
Class Test
{
static void Main () {
EditBox editbox = new EditBox ();
EditBox. Paint (); Error:no such method
IControl control = EditBox;
Control. Paint (); Calls EditBox ' s Paint implementation
}
}