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

如果類別實作兩個具有相同簽章成員的介面,則在類別上實作該成員會造成這兩個介面都使用該成員進行實作。 在下列範例中,所有對 Paint 的呼叫都會叫用相同的方法。 第一個範例會定義類型:

public interface IControl
{
    void Paint();
}
public interface ISurface
{
    void Paint();
}
public class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}

下列範例會呼叫方法:

SampleClass sample = new SampleClass();
IControl control = sample;
ISurface surface = sample;

// The following lines all call the same method.
sample.Paint();
control.Paint();
surface.Paint();

// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass

但您可能不想要針對這兩個介面呼叫相同的實作。 若要根據使用的介面呼叫不同的實作,您可以明確地實作介面成員。 明確介面實作是僅透過指定介面呼叫的類別成員。 請在類別成員的前面加上介面名稱和句號來命名類別成員。 例如:

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

類別成員 IControl.Paint 只能透過 IControl 介面取得,ISurface.Paint 只能透過 ISurface 取得。 這兩種方法實作是分開的,都無法直接在類別上使用。 例如:

SampleClass sample = new SampleClass();
IControl control = sample;
ISurface surface = sample;

// The following lines all call the same method.
//sample.Paint(); // Compiler error.
control.Paint();  // Calls IControl.Paint on SampleClass.
surface.Paint();  // Calls ISurface.Paint on SampleClass.

// Output:
// IControl.Paint
// ISurface.Paint

在兩個介面各自宣告同名之不同成員的情況下 (例如屬性和方法),也可以使用明確實作來解決。 若要實作這兩個介面,類別必須針對屬性 P 和 (或) 方法 P 使用明確實作,來避免編譯器錯誤。 例如:

interface ILeft
{
    int P { get;}
}
interface IRight
{
    int P();
}

class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get { return 0; } }
}

明確介面實作沒有存取修飾詞,因為它無法當做其定義類型的成員來存取。 相反地,它只有在透過介面的執行個體呼叫時才能存取。 如果您指定明確介面實作的存取修飾詞,您會收到編譯器錯誤 CS0106。 如需詳細資訊,請參閱 interface (C# 參考)

您可以定義介面中所宣告成員的實作。 如果類別從介面繼承方法實作,則該方法只能透過介面類型的參考來存取。 繼承的成員不會顯示為公用介面的一部分。 下列範例會定義介面方法的預設實作:

public interface IControl
{
    void Paint() => Console.WriteLine("Default Paint method");
}
public class SampleClass : IControl
{
    // Paint() is inherited from IControl.
}

下列範例會叫用預設實作:

var sample = new SampleClass();
//sample.Paint();// "Paint" isn't accessible.
var control = sample as IControl;
control.Paint();

任何實作 IControl 介面的類別都可以覆寫預設 Paint 方法,作為公用方法或明確介面實作。

另請參閱