C #-based interface basic tutorial 5

Source: Internet
Author: User

Section 5 interface implementation

1. explicitly implement interface members

To implement the interface, the class can define the Explicit interface member execution bodies (Explicit interface member implementations ). The explicit interface member execution body can be a method, an attribute, an event, or an index indicator. The definition must be consistent with the full name of the member.

Using System;
Interface ICloneable {
Object Clone ();
}
Interface IComparable {
Int CompareTo (object other );
}
Class ListEntry: ICloneable, IComparable {
Object ICloneable. Clone (){...}
Int IComparable. CompareTo (object other ){...}
}

In the above Code, ICloneable. Clone and IComparable. CompareTo are the execution bodies of explicit interface members.

Note:

1. The explicit interface member execution body cannot be accessed through full names in method call, attribute access, and index indicator access. In fact, the execution body of an explicit interface member can only be accessed through the interface instance and only by referencing the interface member name.

2. The execution body of an explicit interface member cannot use any access limiters, and abstract, virtual, override, or static modifiers cannot be added.

3. The explicit interface member execution body has different access methods than other members. Because it cannot be accessed by full name in method call, attribute access, and index indicator access, the explicit interface member execution body is private in a sense. However, they can also be accessed through the instance of the interface, but also have a certain public nature.

4. Only when the class is defined, the interface name is written in the base class list, when the full names, types, and return types defined in the class are exactly the same as the execution bodies of explicit interface members, the execution bodies of explicit interface members are valid. For example:

Class Shape: ICloneable {
Object ICloneable. Clone (){...}
Int IComparable. CompareTo (object other ){...}
}
An explicit interface member execution body has two purposes:

1. Because the execution body of the explicit interface member cannot be accessed through the instance of the class, the interface implementation part can be separately separated from the public interface. If a class only uses this interface internally, and the class user does not directly use this interface, this explicit interface member execution body can play a role.

2. Explicit interface member execution bodies avoid confusion between interface members due to the same name. If a class wants to adopt different implementation methods for interface members with the same name and return type, it must use the explicit interface member execution body. If there is no explicit interface member execution body, the class cannot be implemented for interface members of different names and return types.

The following definition is invalid because the IComparable interface is not displayed in the base class list during Shape Definition.

Class Shape: ICloneable
{
Object ICloneable. Clone (){...}
}
Class Ellipse: Shape
{
Object ICloneable. Clone (){...}
}

It is incorrect to define ICloneable. Clone in Ellipse, because even if Ellipse implicitly implements the ICloneable interface, ICloneable still does not explicitly appear in the base class list defined by Ellipse.

The full name of an interface member must correspond to the member defined in the interface. In the following example, the execution body of the explicit interface member 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 ){...}
}
 

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

In the following example, the size of the box is displayed in both the metric and imperial units. The Box class inherits the IEnglishDimensions and IMetricDimensions interfaces, which indicate different weights. The two interfaces have the same member name Length and Width.

Program list 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 * 2.54f;
}
Float IMetricDimensions. Width (){
Return widthInches * 2.54f;
}
Public static void Main (){
// Define an object "myBox "::
Box myBox = new Box (30366f, 20366f );
// Define an interface "eDimensions "::
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
// Output:
System. Console. WriteLine ("Length (in): {0}", eDimensions. Length ());
System. Console. WriteLine ("Width (in): {0}", eDimensions. Width ());
System. Console. WriteLine ("Length (cm): {0}", mDimensions. Length ());
System. Console. WriteLine ("Width (cm): {0}", mDimensions. Width ());
}
}

Output: Length (in): 30, Width (in): 20, Length (cm): 76.2, Width (cm): 50.8

Code discussion: If you want to use the English Unit for the default measurement, implement the Length and Width methods 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 * 2.54f;
}
Float IMetricDimensions. Width (){
Return widthInches * 2.54f;
}

In this case, you can access the imperial unit from the class instance, 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. inherited interface implementation

The interface is immutable, but this does not mean that the interface is no longer evolving. Similar to the inheritance of classes, interfaces can also be inherited and developed.

Note: interface inheritance is different from class inheritance. First, class inheritance not only describes inheritance, but also implements inheritance. interface inheritance only describes inheritance. That is to say, the derived class can inherit the method implementation of the base class, while the derived interface only inherits the description of the member methods of the parent interface, but does not inherit the implementation of the parent interface. Secondly, C # class inheritance only allows single inheritance, but interface inheritance allows multiple inheritance. A subinterface can have multiple parent interfaces.

Interfaces can be inherited from zero or multiple interfaces. When the interface is retransmitted from multiple interfaces, use ":" followed by the inherited interface name, and use "," to separate multiple interface names. The inherited interface should be accessible. For example, inheritance from interfaces of the private or internal type is not allowed. The interface cannot be inherited directly or indirectly from itself. Similar to class inheritance, interface inheritance also forms a hierarchy between interfaces.

See 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 {}

The inheritance of an interface inherits all the members of the interface. In the above example, both the interface ITextBox and IListBox inherit from the interface IControl and inherit the painting method of the interface IControl. The IComboBox interface inherits from the ITextBox and IListBox interfaces. Therefore, it should inherit the SetText method of the ITextBox interface, the SetItems method of the IListBox interface, and the IControl painting method.
A class inherits all the interface implementation programs provided by its basic class.

Without explicitly implementing an interface, a derived class cannot change its interface ing inherited from its basic class in any way. For example

Interface IControl {
Void Paint ();
}
Class Control: IControl {
Public void Paint (){...}
}
Class TextBox: Control {
New public void Paint (){...}
}

The method Paint in TextBox hides the method Paint in Control, but does not change the ing from Control. Paint to IControl. Paint. Calling Paint through class instances and interface instances will have the following impact:

Control c = new Control ();
TextBox t = new TextBox ();
IControl ic = c;
IControl it = t;
C. Paint (); // affects Control. Paint ();
T. Paint (); // the TextBox. Paint ();
Ic. Paint (); // affects Control. Paint ();
It. Paint (); // affects Control. Paint ();

However, when an interface method is mapped to a virtual method in a class, the derived class cannot overwrite this virtual method and change the implementation function of the interface. For example, rewrite the preceding statement

Interface IControl {
Void Paint ();
}
Class Control: IControl {
Public virtual void Paint (){...}
}
Class TextBox: Control {
Public override void Paint (){...}
}

The following result is displayed:

Control c = new Control ();
TextBox t = new TextBox ();
IControl ic = c;
IControl it = t;
C. Paint (); // affects Control. Paint ();
T. Pain

Related Article
Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.