Home>

Section 1 Interface

Interface (interface) is used to define the contract of a program.The class or structure that implements the interface must be strictly consistent with the definition of the interface.With this agreement,You can put aside the limitations of the programming language (in theory). Interfaces can inherit from multiple base interfaces,A class or structure can implement multiple interfaces.Interfaces can contain methods, properties, events, and indexers.The interface itself does not provide implementations of the members it defines.An interface specifies only the members that must be provided by the class or interface that implements the interface.

Interface is like a template,This template defines the methods that an object must implement,The purpose is to make these methods available as interface instances.The interface cannot be instantiated.A class can implement multiple interfaces and be indexed through these implemented interfaces.Interface variables can only index instances of classes that implement that interface.example:

interface imyexample {
String this [int index] {get;set;}
Event eventhandler even;
Void find (int value);
String point {get;set;}
}
public delegate void eventhandler (object sender, event e);

The interface in the above example contains an index this, an event even, a method find, and an attribute point.

Interface can support multiple inheritance.Just like in the following example,The interface "icombobox" inherits from both "itextbox" and "ilistbox".

interface icontrol {
void paint ();
}
interface itextbox:icontrol {
void settext (string text);
}
interface ilistbox:icontrol {
void setitems (string [] items);
}
interface icombobox:itextbox, ilistbox {}

Classes and structures can instantiate multiple interfaces.Just like in the following example,The class "editbox" inherits the class "control" and also inherits from "idatabound" and "icontrol".

interface idatabound {
Void bind (binder b);
}
public class editbox:control, icontrol, idatabound {
Public void paint ();
Public void bind (binder b) {...}
}

In the code above,The "paint" method comes from the "icontrol" interface;The "bind" method comes from the "idatabound" interface,Both are implemented in the "editbox" class as "public".

Explanation:

1. The interface in c#is defined independently of the class.This is in contrast to the C++ model,An interface is actually an abstract base class in C++.

2, interfaces and classes can inherit multiple interfaces.

3, and a class can inherit a base class,Interfaces cannot inherit classes at all.This model avoids the multiple inheritance problem of C++,Implementations in different base classes in C++ may conflict.As a result, complex mechanisms such as virtual inheritance and explicit scope are no longer needed.C#'s simplified interface model helps speed up application development.

4. An interface defines a reference type with only abstract members.What an interface in c#actually does,There are only method flags,But no code is executed at all.This implies that an interface cannot be instantiated,You can only instantiate an object derived from this interface.

5. Interface can define methods, properties and indexes.So, comparing a class,The particularity of the interface is:when defining a class,Can be derived from multiple interfaces,And you can only derive from the only class.

Interfaces and components

Interface describes the services provided by the component.Interactions occur between components and between components and between customers and components.So once the component is released,It can only provide reasonable and consistent services through predefined interfaces.This stability between interface definitions enables customer application developers to build robust applications.A component can implement multiple component interfaces,A specific component interface can also be implemented by multiple components.

The component interface must be self-describing.This means that the component interface should not depend on the specific implementation,Separating the implementation from the interface completely eliminates the coupling between the user of the interface and the implementer of the interface,Enhanced the degree of encapsulation of information.It also requires that component interfaces use a language that is independent of the component implementation.The current description standard for component interfaces is the idl language.

Since interfaces are protocols between components,So once the component's interface is published,The component producer should keep the interface as unchanged as possible,Any changes in interface syntax or semantics,It is possible that the contact between existing components and customers will be broken.

Each component is autonomous,Has its unique features,Can only communicate with the outside world through the interface.When a component needs to provide new services,This can be achieved by adding new interfaces.Does not affect customers who already have the original interface.And new customers can choose new interfaces to get services again.

Component programming

The component programming method inherits and develops the object-oriented programming method.It applies object technology to system design,The abstraction of the realization process of object-oriented programming is made.We can use the component programming approach as an architectural level approach to constructing the system,And components can be easily implemented using object-oriented methods.

Component programming emphasizes true software reusability and high interoperability.It focuses on the production and assembly of components,These two aspects together form the core of component programming.The generation process of components is not only a requirement of the application system,The component market itself has also promoted the development of components,Promote communication and cooperation between software vendors.The assembly of components allows software products to be quickly built using a method similar to building blocks,Not only can shorten the development cycle of software products,It also improves the stability and reliability of the system.

The method of component programming has the following characteristics:

1. Independence of programming language and development environment;

2, the transparency of component positions;

3, component process transparency;

4, scalability;

5. Reusability;

6. Strong infrastructure;

7. Public services at the system level;

C#language because of its many advantages,Great for component programming.But this is not to say that C#is a component programming language,It's not that c#provides tools for component programming.We have stated many times thatComponents should have features that are independent of the programming language.Readers are reminded of this:the component model is a specification,No matter what programming language is used to design the component,Must comply with this norm.Like the example of assembling a computer,As long as the accessories specifications and interfaces provided by various manufacturers meet our unified standards,These accessories work together to work together,The same goes for component programming.We just say,Using c#language for component programming will bring us greater convenience.

Know what an interface is,The next step is how to define the interface.See the next section-Defining Interfaces.

Section 2 Defining Interfaces

Technically,An interface is a set of data structures containing functional methods.Through this set of data structures,The client code can call the functionality of the component object.

Define the general form of the interface as:

[attributes] [modifiers] interface identifier [:base-list] {interface-body} [;]

Explanation:

1, attributes (optional):additional definitive information.

2, modifiers (optional):Allowed modifiers are new and four access modifiers.They are:new, public, protected, internal, private. The same modifier is not allowed to appear multiple times in an interface definition.new

Modifiers can only appear in nested interfaces,Indicates that the inherited member of the same name is covered.The public, protected, internal, and private modifiers define access to the interface.

3. Indicators and events.

4, identifier:Interface name.

5. base-list (optional):a list containing one or more explicit base interfaces,Interfaces are separated by commas.

6. interface-body:Definition of interface members.

7. Interfaces can be members of namespaces or classes.And can include signatures of the following members:methods, properties, indexers.

8. An interface can inherit from one or more base interfaces.

The concept of interface is very similar in c#and java.The key word of interface is interface, an interface can extend one or more other interfaces.By convention,The name of the interface begins with an uppercase "i". The following code is an example of the c#interface,It is exactly the same as the interface in java:

interface ishape {
Void draw ();
}
</pre>
</div>
<p>
If you derive from two or more interfaces,The comma-separated list of parent interface names,As shown in the following code:
</p>
<div>
<pre>
interface inewinterface:iparent1, iparent2 {}
</pre>
</div>
<p>
However, unlike java, interfaces in c#cannot contain fields. Also note that
In c#, all methods within an interface are public by default.
In java, method definitions can have public modifiers (even if this is not necessary), but in c#it is illegal to specify public modifiers for methods of an interface.
For example, the following c#interface will generate a compilation error.
</p>
<div>
<pre>
interface ishape {public void draw ();}

The following example defines an interface named icontrol, which contains a member method paint:

interface icontrol {
Void paint ();
}

In the following example,Interface iinterface inherits from two base interfaces ibase1 and ibase2:

interface iinterface:ibase1, ibase2 {
Void method1 ();
Void method2 ();
}

Interfaces can be implemented by classes.The identifier of the implemented interface appears in the base list of the class.E.g:

class class:iface, iface {
//class members.
//http://www.cnblogs.com/roucheng/
}

When the base list of a class contains both a base class and an interface,The base class appears first in the list.E.g:

class classa:baseclass, iface1, iface2 {
//Class members.
}

The following code segment defines the interface iface, which has only one method:

interface iface {
Void showmyface ();
}

Cannot instantiate an object from this definition,But you can derive a class from it.Therefore, the class must implement the showmyface abstract method:

class cface:iface
{
Public void showmyface () {
Console.writeline ("implementation");
}
}

Base Interface

An interface can inherit from zero or more interfaces,Those explicit base interfaces are called this interface.When an interface has more explicit base interfaces than zero,Then the form in the definition of the interface is,The interface identifier is followed by a list of base interface identifiers separated by a colon ":" and a comma ",".

Interface base:

:Interface type list description:

1. The explicit base interface of an interface must be at least as accessible as the interface itself.For example, specifying a private or internal interface in the base interface of a public interface is wrong.

2. It is wrong for an interface to inherit directly or indirectly from itself.

3, the base interface of the interface are all explicit base interfaces,And is their base interface.in other words,The set of base interfaces consists entirely of explicit base interfaces and their explicit base interfaces and so on.In the example below

interface icontrol {
Void paint ();
}
interface itextbox:icontrol {
Void settext (string text);
}
interface ilistbox:icontrol {
Void setitems (string [] items);
}
interface icombobox:itextbox, ilistbox {}

The base interfaces of icombobox are icontrol, itextbox, and ilistbox.

4. An interface inherits all members of its base interface.in other words,The interface icombobox above inherits the members settext and setitems just like paint.

5. A class or structure that implements an interface also implicitly implements the base interface of all interfaces.

Interface body

interface The interface body of an interface defines the members of the interface.

interface-body:
{interface-member-declarationsopt}

Defining interfaces is mainly defining interface members,See the next section-Defining Interface Members.

Section 3 Defining Interface Members

Interfaces can contain one or more members,These members can be methods, properties, index indicators, and events.But not constants, fields, operators, constructors, or destructors,It cannot contain any static members.Interface definition creates a new definition space,And the interface member definition directly contained in the interface definition introduces new members into the definition space.

Description:

1. The members of an interface are members inherited from the base interface and members defined by the interface itself.

2. Interface definition can define zero or more members.The members of an interface must be methods, properties, events, or indexers.Interfaces cannot contain constants, fields, operators, instance constructors, destructors, or types.Nor can it contain any kind of static members.

3. Define an interface,The interface contains one for each possible kind of member:methods, properties, events, and indexers.

4. The default access method of interface members is public. Interface member definitions cannot contain any modifiers,For example, you cannot add abstract, public, protected, internal, private, virtual, override, or static modifiers before defining a member.

5. The members of the interface cannot have the same name.The inherited members do not need to be defined anymore.But an interface can define a member with the same name as an inherited member,At this time we say that the interface members cover inherited members,This will not cause an error,But the compiler will give a warning.The way to turn off the warning is to add a new keyword before the member definition. But if you don't override the members in the parent interface,Using the new keyword causes the compiler to issue a warning.

6. The name of the method must be different from the names of all properties and events defined in the same interface.In addition, the signature of a method must be different from the signatures of all other methods defined in the same interface.

7. The name of the attribute or event must be different from the names of all other members defined in the same interface.

8. The signature of one indexer must be different from the signatures of all other indexers defined in the same interface.

9, attributes, return types (return-type), identifiers, and formal-parameter-lis in interface method declarations have the same meaning as those in a class method declaration .An interface method declaration does not allow specifying a method body,The declaration usually ends with a semicolon.

10. The accessor declared in the interface attribute corresponds to the accessor declared in the class attribute.Except for the accessor body, a semicolon must usually be used.Therefore, whether the attribute is read-write, read-only, or write-only,The access characters are completely determined.

11. The attributes, type, and formal-parameter-list in the interface index declaration have the same meaning as those of the class index declaration.

interface In the following example, the interface imytest contains the index indicator, event e, method f, and attribute p:

interface imytest {
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);
</pre>
</div>
<p>interface In the following example, the interface isttinglist contains an interface for each possible type member:a method,An attribute,An event and an index.
</p>
<div>
<pre>
public delegate void stringlistevent (istringlist sender);
public interface istringlist
{
Void add (string s);
Int count {get;}
Event stringlistevent changed;
String this [int index] {get;set;}
}

Full name of the interface member

Using interface members can also use fully qualified names. The full name of the interface is constructed like this.The interface name is added with a dot "." Followed by the member name. For example for the following two interfaces:

interface icontrol {
Void paint ();
}
interface itextbox:icontrol {
Void gettext (string text);
}

The full name of paint is icontrol.paint, and the full name of gettext is itextbox.gettext. Of course, the member name in the full name must be defined in the interface,For example, using itextbox.paint. Is not reasonable.

If the interface is a member of a namespace,The full name must also include the name of the namespace.

namespace system
{
Public interface idatatable {
Object clone ();
}
}

The full name of the clone method is system.idatatable.clone.

The interface is defined,The next step is how to access the interface.Please see the next section-Access Interface

Section 4:Access Interface

Access to interface members

interface The rules for calling interface methods and using index pointer access are the same as in the case of the class.If the names of the lower members are consistent with the inherited higher members,Then the lower-level members will cover the higher-level members with the same name.But because the interface supports multiple inheritance,In multiple inheritance,If two parent interfaces contain members with the same name,This creates ambiguity (which is one of the reasons for the multiple inheritance mechanism of classes being cancelled in c#), and you need to define it explicitly:

using system;
interface isequence {
Int count {get;set;}
}
interface iring {
Void count (int i);
}
//http://www.cnblogs.com/roucheng/
interface iringsequence:isequence, iring {}
Class ctest {
Void test (iringsequence rs) {
/Rs.count ();wrong, count is ambiguous
/Rs.count =;wrong, count is ambiguous
((Isequence) rs) .count =;//correct
((Iring) rs) .count ();//correctly call iring.count
}
}

In the example above,The first two statements, rs .count (1) and rs .count=1 will create ambiguityLeading to compile-time errors,So you must explicitly assign the parent interface type to rs,This assignment does not incur additional overhead at runtime.

Look at the following example again:

using system;
interface iinteger {
Void add (int i);
}
interface idouble {
Void add (double d);
}
interface inumber:iinteger, idouble {}
Class cmytest {
Void test (inumber num) {
//num.add ();error
Num.add (.);//correct
((Iinteger) n) .add ();//correct
((Idouble) n) .add ();//correct
}
}

Calling num.add (1) results in ambiguity,Because the parameter types of the candidate overload methods are applicable.However, calling num.add (1.0) is allowed,Because 1.0 is a floating-point parameter type that does not match the parameter type of the method iinteger.add (),Only idouble.add is applicable.But as long as explicit assignments are added,There will never be ambiguity.

The problem of multiple inheritance of interfaces also brings problems in member access.E.g:

interface ibase {
Void fway (int i);
}
interface ileft:ibase {
New void fway (int i);
}
interface iright:ibase
{void g ();}
interface iderived:ileft, iright {}
class ctest {
Void test (iderived d) {
D. Fway ();//call ileft. Fway http://www.cnblogs.com/roucheng/
((Ibase) d). Fway ();//call ibase. Fway
((Ileft) d). Fway ();//call ileft. Fway
((Iright) d) .fway ();//call ibase. Fway
}
}

In the above example, the method ibase.fway is overridden by the ileft member method fway in the derived interface ileft. So the call to d.fway (1) is actually called.Although from the inheritance path of ibase->iright->iderived,The ileft.fway method is not overridden.We just need to keep this in mind:once members are covered,All access to it is "blocked" by future members.

Class implementation of interface

We have said before,The interface definition does not include the implementation part of the method.Interfaces can be implemented through classes or structures.We mainly talk about implementing interfaces through classes.When using classes to implement interfaces,The name of the interface must be included in the base class list in the class definition.

The following example gives an example of an interface implemented by a class.Where isequence is a queue interface,Provides a member method add () to add an object to the tail of the queue, iring is a circular table interface,Provides a method insert (object obj) to insert an object into the ring, which returns the position of the insertion.The class ringsquence implements the interface isequence and interface iring.

using system;
interface isequence {
Object add ();
}
interface isequence {
Object add ();
}
interface iring {
Int insert (object obj);
}
class ringsequence:isequence, iring
{
Public object add () {…}
Public int insert (object obj) {…}
}

If the class implements an interface,The class also implicitly inherits all the parent interfaces of the interface,It doesn't matter if these parent interfaces are listed in the base class table of the class definition.Look at the following example:

using system;
interface icontrol {
Void paint ();
}
interface itextbox:icontrol {
Void settext (string text);
}
interface ilistbox:icontrol {
Void setitems (string [] items);
}
interface icombobox:itextbox, ilistbox {}

Here, the interface icombobox inherits itextbox and ilistbox. The textbox class implements not only the interface itextbox, but also the parent interface icontrol of interface itextbox.

We have seen before,A class can implement multiple interfaces.Look at the following example again:

interface idatabound {
Void bind (binder b);
}
public class editbox:control, icontrol, idatabound {
Public void paint ();
Public void bind (binder b) {...}
}

The editbox class is derived from the class control and implements icontrol and idatabound. In the previous example, the paint method in the interface icontrol and the bind method in the idatabound interface are implemented with public members in the editbox class.c#provides an alternative way to implement these methods,This prevents the class that implements them from making these members public.Interface members can be implemented with valid names.For example, the class editbox can be implemented as methods icontrol.paint and idatabound.bind.

public class editbox:icontrol, idatabound {
Void icontrol.paint () {...}
Void idatabound.bind (binder b) {...}
}

Because each member is implemented by externally assigning interface members,So members implemented in this way are called external interface members.External interface members can be called only through the interface.For example, the implementation of editbox in the paint method can be called just by creating an icontrol interface.

class test {
Static void main () {
Editbox editbox=new editbox ();
Editbox.paint ();//Error:editbox has no paint event
Icontrol control=editbox;
Control.paint ();//call editbox's paint event
}
}
</pre>
</div>
<p>
In the above example, the editbox class inherits from the control class and implements both the icontrol and idatabound interfaces. The paint method in editbox comes from the icontrol interface and the bind method comes from the idatabound interface. Both are implemented as public members in the editbox class.
Of course, in C#we can also choose not to implement the interface as a public member.
</p>
<p>
If each member clearly indicates the interface being implemented,The interfaces that are implemented in this way are called explicit interface members. In this way we rewrite the above example:
</p>
<div>
<pre>
public class editbox:icontrol, idatabound {
Void icontrol.paint () {…}
Void idatabound.bind (binder b) {…}
}
</pre>
</div>
<p>
Explicit interface members can only be called through the interface.
E.g:
</p>
<div>
<pre>
class ctest {
Static void main () {
Editbox editbox=new editbox ();
Editbox.paint ();//Error:different method
Icontrol control=editbox;
Control.paint ();//Call the paint method of editbox
}
}
</pre>
</div>
<p>
The call to editbox.paint () in the above code is wrong,Because editbox itself does not provide this method.
control.paint () is the correct way to call it.
</p>
<p>
Note:The interface itself does not provide implementations of the defined members,It just states those members,These members must rely on the support of classes or other interfaces that implement the interface.
</p>
<p>
I know how to access the interface,We also need to know how to implement the interface,To implement the c#interface, see the next section-Implementing the interface
</p>
<p>
<strong>
Section V. Implementing the Interface
</strong>
</p>
<p>
<Strong>
1. Explicitly implement interface members
</strong>
</p>
<p>
In order to implement the interface,Classes can define explicit interface member implementations. Explicit interface member executors can be the definition of a method, a property, an event, or an index indicator,The definition of the full name corresponding to that member should be consistent.
</p>
<div>
<pre>
using system;
interface icloneable {
Object clone ();
}
interface icomparable {
Int compareto (object other);
}
class listentry:icloneable, icomparable {
Object icloneable.clone () {…}
Int icomparable.compareto (object other) {…}
}
</pre>
</div>
<p>
IcIn the above code, icloneable.clone and icomparable.compareto are the members of the explicit interface.
</p>
<p>
<Strong>
Explanation:
</strong>
</p>
<p>
1. You cannot access explicit interface member executors with full names in method calls, property accesses, and index pointer accesses.
In fact, an explicit interface member executor can only pass an instance of the interface,Just reference the member name of the interface to access.
</p>
<p>
2, Explicit interface member executors cannot use any access restrictors,Nor can you add abstract, virtual, override, or static modifiers.
</p>
<p>
3. Explicit interface member executors and other members have different access methods.
Because full name access is not available in method calls, property accesses, and index pointer accesses,Explicit interface member executors are private in a sense.
But they can be accessed through instances of the interface,It also has a certain public nature.
</p>
<p>
4. Only when class is defined,Write the interface name in the base class list,When the full name, type, and return type defined in the class are exactly the same as the explicit interface member executor body,Explicit interface member executors are valid,E.g:
</p>
<div>
<pre>
class shape:icloneable {
object icloneable.clone () {…}
int icomparable.compareto (object other) {…}
}

Using explicit interface member executors usually has two purposes:

1, because explicit interface member executors cannot be accessed through instances of the class,This can separate the implementation part of the interface from the public interface.If a class uses the interface only internally,The user of the class will not directly use this interface,This explicit interface member executor can help.

2. Explicit interface member executors avoid confusion among interface members because of the same name.If a class wants different implementations for interface members with the same name and return type,This requires the use of explicit interface member executors.If there is no explicit interface member executor,Then for interface members with different names and return types,Classes cannot be implemented either.

The following definitions are invalid,Because the interface icomparable does not appear in the base class list when the shape is defined.

class shape:icloneable
 {
 object icloneable.clone () {…}
 }
 class ellipse:shape
 {
 object icloneable.clone () {…}
 }

definition It is wrong to define icloneable.clone in ellipseBecause even though ellipse implicitly implements the interface icloneable, icloneable still does not appear explicitly in the list of base classes defined by ellipse.

The full name of the interface member must correspond to the member defined in the interface.As in the following example,The explicit interface member executor of paint must be written as icontrol.paint.

using system;
 interface icontrol
 {
 Void paint ();
 }
 interface itextbox:icontrol
 {
 Void settext (string text);
 }
 class textbox:itextbox
 {
 Void icontrol.paint () {…}
 Void itextbox.settext (string text) {…}
 }

class A class that implements an interface can explicitly implement members of that interface.When a member is explicitly implemented,This member cannot be accessed through a class instance,The member can only be accessed through an instance of the interface.Explicit interface implementation also allows programmers to inherit two interfaces that share the same member name,A separate implementation is provided for each interface member.

In the following example, the size of the frame is displayed in both metric and imperial units.The box class inherits ienglishdimensions and imetricdimensions.They represent different systems of weights and measures.Both interfaces have the same member names length and width.

Listing 1 demoninterface.cs

interface ienglishdimensions {
 float length ();
 float width ();
 }
 interface imetricdimensions {
 float length ();
 float width ();
 }
 class box:ienglishdimensions, imetricdimensions {
 float lengthinches;
 float widthinches;
 public box (float length, float width) {
 lengthinches=length;
 widthinches=width;
 }
 float ienglishdimensions.length () {
 return lengthinches;
 }
 float ienglishdimensions.width () {
 return widthinches;
 }
 float imetricdimensions.length () {
 return lengthinches * .f;
 }
 float imetricdimensions.width () {
 return widthinches * .f;
 }
 public static void main () {
 //Define a real class object "mybox" ::
 box mybox=new box (.f, .f);
 //define an interface "edimensions" ::
 ienglishdimensions edimensions=(ienglishdimensions) mybox;
 imetricdimensions mdimensions=(imetricdimensions) mybox;
 //Output:
 system.console.writeline ("length (in):{}", edimensions.length ());
 system.console.writeline ("width (in):{}", edimensions.width ());
 system.console.writeline ("length (cm):{}", mdimensions.length ());
 system.console.writeline ("width (cm):{}", mdimensions.width ());
 }
 }

Output:length (in):30, width (in):20, length (cm):76.2, width (cm):50.8

Code discussion:If i want the default measurement to be in English units,Please implement the two methods length and width normally,And explicitly implement the length and width methods from the imetricdimensions interface:

public float length () {
 return lengthinches;
 }
 public float width () {
 return widthinches;
 }
 float imetricdimensions.length () {
 return lengthinches * .f;
 }
 float imetricdimensions.width () {
 return widthinches * .f;
 }

In this situation,Imperial units can be accessed from class instances,And access the metric unit from the interface instance:

system.console.writeline ("length (in):{0}", mybox.length ());
system.console.writeline ("width (in):{0}", mybox.width ());
system.console.writeline ("length (cm):{0}", mdimensions.length ());
system.console.writeline ("width (cm):{0}", mdimensions.width ());

2. Inherit interface implementation

Interface is invariant,But this does not mean that the interface is no longer developing.Similar to class inheritance,Interfaces can also inherit and evolve.

Note:Interface inheritance is different from class inheritance.First, class inheritance is not just about inheritance.And also implement inheritance;And interface inheritance is just about inheritance.That is,Derived classes can inherit the base class method implementation,The derived interface only inherits the member method descriptions of the parent interface.Without inheriting the implementation of the parent interface,Second, class inheritance in c#only allows single inheritance.But interface inheritance allows multiple inheritance,A child interface can have multiple parent interfaces.

Interfaces can inherit from zero or more interfaces.When inheriting from multiple interfaces,Use ":" followed by the name of the interface being inherited,Separate multiple interface names with ",". The inherited interface should be accessible.For example, inheriting from a private or internal interface is not allowed.Interfaces are not allowed to inherit directly or indirectly from themselves.Similar to class inheritance,Interface inheritance also forms a hierarchy between interfaces.

Look at the following example:

using system;
 interface icontrol {
 void paint ();
 }
 interface itextbox:icontrol {
 void settext (string text);
 }
 interface ilistbox:icontrol {
 void setitems (string [] items);
 }
 interface icombobox:itextbox, ilistbox {}

of The inheritance of an interface inherits all members of the interface,In the above example, the interfaces itextbox and ilistbox both inherit from the interface icontrol, and thus inherit the paint method of the interface icontrol. The interface icombobox inherits from the interfaces itextbox and ilistbox, so it should inherit the settext method and ilistbox setitems method of the interface, and the icontrol paint method.

A class inherits all the interface implementors provided by its base classes.

Do not implement an interface explicitly,A derived class cannot change the interface mapping it inherits from its base class in any way.For example, in a statement

interface icontrol {
 void paint ();
 }
 class control:icontrol {
 public void paint () {...}
 }
 class textbox:control {
 new public void paint () {...}
 }

PaintThe method paint in the textbox hides the method paint in the control, but does not change the mapping from control.paint to icontrol.paint. Calling paint through class instances and interface instances will have the following effects

control c=new control ();
 textbox t=new textbox ();
 icontrol ic=c;
 icontrol it=t;
 c.paint ();//affect control.paint ();
 t.paint ();//affects textbox.paint ();
 ic.paint ();//affects control.paint ();
 it.paint ();//affects control.paint ();

But when an interface method is mapped to a virtual method in a class,It is impossible for a derived class to override this virtual method and change the implementation of the interface.For example, rewrite the above statement as

interface icontrol {
 void paint ();
 }
 class control:icontrol {
 public virtual void paint () {...}
 }
 class textbox:control {
 public override void paint () {...}
 }
</pre>
</div>
<p>
I will see the following results:
</p>
<div>
<pre>
control c=new control ();
textbox t=new textbox ();
icontrol ic=c;
icontrol it=t;
c.paint ();//affects control.paint ();
t.paint ();//affects textbox.paint ();
ic.paint ();//affects control.paint ();
it.paint ();//affects textbox.paint ();
</pre>
</div>
<p>
Because explicit interface member implementors cannot be declared virtual,It is not possible to override an explicit interface member implementor.
It is valid for an explicit interface member implementer to call another method,The other method can be declared virtual so that derived classes can override it.
E.g:
</p>
<div>
<pre>
 interface icontrol {
 Void paint ();
 }
 class control:icontrol {
 Void icontrol.paint () {paintcontrol ();}
 Protected virtual void paintcontrol () {...}
 }
 class textbox:control {
 Protected override void paintcontrol () {...}
 }

Here, classes inherited from control can specialize the implementation of icontrol.paint by overriding the method paintcontrol.

3.Reimplement the interface

We have already introduced,Derived classes can overload member methods defined in the base class.Similar concepts are introduced into the implementation of interfaces by classes,Called interface re-implementation. A class that inherits an interface implementation can reimplement the interface.This interface requirement has appeared in the base class list of the class definition.The re-implementation of the interface must also strictly adhere to the rules for the first implementation of the interface,The derived interface mapping does not have any effect on the interface mapping established for the reimplementation of the interface.

The following code gives an example of interface reimplementation:

interface icontrol {
Void paint ();
Class control:icontrol



}
 
 
 }
 
 
 }
 
 }


}


}



}


}
}



}


}
}


}
class class1 {


}


}

E.g:

 }
 
 }
 }
 
 }
 
 }
 }
 
 }
 
 }
 
 }
 }

Look at the following example:

 }
 
 }
 Get
 
 }
 
 
 }
 
 
 }
 
 
 }
 
 }
 
 
 }

In the example above,

but in fact,

usually,

In these cases,



{}
</pre>
</div>
<p>


</p>
<p>
<Strong>

</strong>
</p>
<p>



</p>
<div>
<pre>
 {
 public static void main ()
 {
 }
 }

by default,

using system.runtime.interopservices;
 
 
 {
 void run ();
 void pause ();
 
 
 
 
 
 
 }
</pre>
</div>
<p>

</p>
<p>

</p>
<p>
<Strong>

</strong>
</p>
<div>
<pre>
using system;
using system.runtime.interopservices;

{





void run ();
void pause ();













}



{

}
}

{
public static void main (string [] args)
{

if (args.length!=1)
{

return;
}


{

return;
}










console.readline ();
}




}
}
 {
 
 {
 
 
 
 
 }
 }

Explanation:

using system;
 using system.runtime.interopservices;
 class mainapp
 
 
 {
 }
 }

E.g

 
 }
 {
 
 }

E.g

 {
 
 }
 {
 
 
 }
c
  • Previous Understanding of objects and references and inner classes in Java's object-oriented programming
  • Next Raw and complex values ​​in JavaScript