如何明確實作兩個介面的成員 (C# 程式設計指南)
明確的介面實作也可讓程式設計人員實作具有相同成員名稱的兩個介面,並提供每個介面成員不同的實作。 此範例會顯示方塊尺寸的計量和英制單位。 Box 類別實作 IEnglishDimensions 和 IMetricDimensions 兩個介面,代表不同的量值系統。 這兩個介面具有相同的成員名稱,Length 和 Width。
範例
// Declare the English units interface:
interface IEnglishDimensions
{
float Length();
float Width();
}
// Declare the metric units interface:
interface IMetricDimensions
{
float Length();
float Width();
}
// Declare the Box class that implements the two interfaces:
// IEnglishDimensions and IMetricDimensions:
class Box : IEnglishDimensions, IMetricDimensions
{
float lengthInches;
float widthInches;
public Box(float lengthInches, float widthInches)
{
this.lengthInches = lengthInches;
this.widthInches = widthInches;
}
// Explicitly implement the members of IEnglishDimensions:
float IEnglishDimensions.Length() => lengthInches;
float IEnglishDimensions.Width() => widthInches;
// Explicitly implement the members of IMetricDimensions:
float IMetricDimensions.Length() => lengthInches * 2.54f;
float IMetricDimensions.Width() => widthInches * 2.54f;
static void Main()
{
// Declare a class instance box1:
Box box1 = new Box(30.0f, 20.0f);
// Declare an instance of the English units interface:
IEnglishDimensions eDimensions = box1;
// Declare an instance of the metric units interface:
IMetricDimensions mDimensions = box1;
// Print dimensions in English units:
System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
// Print dimensions in metric units:
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
*/
穩固程式設計
如果您想要以英制單位建立預設的量值單位,請按一般方式實作 Length 和 Width 方法,並從 IMetricDimensions 介面明確實作 Length 和 Width 方法:
// Normal implementation:
public float Length() => lengthInches;
public float Width() => widthInches;
// Explicit implementation:
float IMetricDimensions.Length() => lengthInches * 2.54f;
float IMetricDimensions.Width() => widthInches * 2.54f;
在本例中,您可以從類別執行個體存取英制單位,從介面執行個體存取計量單位:
public static void Test()
{
Box box1 = new Box(30.0f, 20.0f);
IMetricDimensions mDimensions = box1;
System.Console.WriteLine("Length(in): {0}", box1.Length());
System.Console.WriteLine("Width (in): {0}", box1.Width());
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
}
另請參閱
- 物件導向程式設計
- 介面
- 如何明確實作介面成員 (部分機器翻譯)