如何明確實作介面成員 (C# 程式設計手冊)

這個範例會宣告介面 (IDimensions) 和類別 (Box),它會明確實作介面成員 GetLengthGetWidth。 成員是透過介面執行個體 dimensions 存取。

範例

interface IDimensions
{
    float GetLength();
    float GetWidth();
}

class Box : IDimensions
{
    float lengthInches;
    float widthInches;

    Box(float length, float width)
    {
        lengthInches = length;
        widthInches = width;
    }
    // Explicit interface member implementation:
    float IDimensions.GetLength()
    {
        return lengthInches;
    }
    // Explicit interface member implementation:
    float IDimensions.GetWidth()
    {
        return widthInches;
    }

    static void Main()
    {
        // Declare a class instance box1:
        Box box1 = new Box(30.0f, 20.0f);

        // Declare an interface instance dimensions:
        IDimensions dimensions = box1;

        // The following commented lines would produce compilation
        // errors because they try to access an explicitly implemented
        // interface member from a class instance:
        //System.Console.WriteLine("Length: {0}", box1.GetLength());
        //System.Console.WriteLine("Width: {0}", box1.GetWidth());

        // Print out the dimensions of the box by calling the methods
        // from an instance of the interface:
        System.Console.WriteLine("Length: {0}", dimensions.GetLength());
        System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
    }
}
/* Output:
    Length: 30
    Width: 20
*/

穩固程式設計

  • 請注意,在 Main 方法中,下列各行因為會產生編譯錯誤所以都已註解。 從類別執行個體無法存取已明確實作的介面成員:

    //System.Console.WriteLine("Length: {0}", box1.GetLength());
    //System.Console.WriteLine("Width: {0}", box1.GetWidth());
    
  • 另請注意,在 Main 方法中,下列幾行會成功列印方塊大小,因為正從介面的執行個體呼叫方法:

    System.Console.WriteLine("Length: {0}", dimensions.GetLength());
    System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
    

另請參閱