第五節
為了實現接口
using System ;
interface ICloneable
{
object Clone( ) ;
}
interface IComparable
{
int CompareTo(object other) ;
}
class ListEntry: ICloneable
{
object ICloneable
int IComparable
}
上面的代碼中ICloneable
說明
class Shape: ICloneable
{
object ICloneable
int IComparable
}
使用顯式接口成員執行體通常有兩個目的
下面的定義是無效的
class Shape: ICloneable
{
object ICloneable
}
class Ellipse: Shape
{
object ICloneable
}
在Ellipse 中定義ICloneable
接口成員的全權名必須對應在接口中定義的成員
using System ;
interface IControl
{
void Paint( ) ;
}
interface ITextBox: IControl
{
void SetText(string text) ;
}
class TextBox: ITextBox
{
void IControl
void ITextBox
}
實現接口的類可以顯式實現該接口的成員
下面例子中同時以公制單位和英制單位顯示框的尺寸
程序清單
interface IEnglishDimensions
{
float Length ( ) ;
float Width ( ) ;
}
interface IMetricDimensions
{
float Length ( ) ;
float Width ( ) ;
}
class Box : IEnglishDimensions
{
float lengthInches ;
float widthInches ;
public Box(float length
{
lengthInches = length ;
widthInches = width ;
}
float IEnglishDimensions
{
return lengthInches ;
}
float IEnglishDimensions
{
return widthInches ;
}
float IMetricDimensions
{
return lengthInches *
}
float IMetricDimensions
{
return widthInches *
}
public static void Main( )
{
//定義一個實類對象
Box myBox = new Box(
// 定義一個接口
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
// 輸出:
System
System
System
System
}
}
輸出
代碼討論
public float Length( )
{
return lengthInches ;
}
public float Width( )
{
return widthInches;
}
float IMetricDimensions
{
return lengthInches *
}
float IMetricDimensions
{
return widthInches *
}
這種情況下
System
System
System
System
From:http://tw.wingwit.com/Article/program/net/201311/15704.html