The interface contains only the signature of a method, property, event, or indexer.the class or struct that implements the interface must implement the interface members specified in the interface definition. in the following example, the class ImplementationClass must implement a method named SampleMethod that does not have parameters and returns void .
Example
1 InterfaceISampleInterface2 {3 voidSampleMethod ();4 }5 6 classImplementationclass:isampleinterface7 {8 //Explicit interface member implementation:9 voidIsampleinterface.samplemethod ()Ten { One //Method implementation. A } - - Static voidMain () the { - //Declare an interface instance. -ISampleInterface obj =NewImplementationClass (); - + //Call the member. - obj. SampleMethod (); + } A}
An interface can be a member of a namespace or class, and can contain signatures for the following members:
Method
Property
Indexer
Event
An interface can inherit from one or more base interfaces.
When a base type list contains a base class and an interface, the base class must be the first item in the list.
A class that implements an interface can explicitly implement members of that interface. an explicitly implemented member cannot be accessed through a class instance, but only through an interface instance.
Example
The following example shows an interface implementation. in this example, the interface contains the property declaration, and the class contains the implementation. Any instance of a class that implements IPoint has integer attributes x and y.
1 InterfaceIPoint2 {3 //Property Signatures:4 intx5 {6 Get;7 Set;8 }9 Ten inty One { A Get; - Set; - } the } - - classPoint:ipoint - { + //Fields : - Private int_x; + Private int_y; A at //Constructor: - PublicPoint (intXinty) - { -_x =x; -_y =y; - } in - //Property Implementation: to Public intx + { - Get the { * return_x; $ }Panax Notoginseng - Set the { +_x =value; A } the } + - Public inty $ { $ Get - { - return_y; the } - SetWuyi { the_y =value; - } Wu } - } About $ classMainClass - { - Static voidprintpoint (IPoint p) - { AConsole.WriteLine ("x={0}, Y={1}", p.x, p.y); + } the - Static voidMain () $ { thePoint P =NewPoint (2,3); theConsole.Write ("My Point:"); the Printpoint (p); the } - } in //output:my point:x=2, y=3
Interface (C # Reference)