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

這個範例會宣告介面 (IDimensions) 和類別 (Box),它會明確實作介面成員 GetLength 和 GetWidth。 成員是透過介面執行個體 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(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:
        //Console.WriteLine($"Length: {box1.GetLength()}");
        //Console.WriteLine($"Width: {box1.GetWidth()}");

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

穩固程式設計

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

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

    Console.WriteLine($"Length: {dimensions.GetLength()}");
    Console.WriteLine($"Width: {dimensions.GetWidth()}");
    

另請參閱