共用方式為


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

如果類別實作了兩個包含相同簽章之成員的介面,則在類別上實作該成員會導致兩個介面都將該成員當做實作 (Implementation) 使用。 在下列範例中,對 Paint 的呼叫所叫用的方法。

class Test 
{
    static void Main()
    {
        SampleClass sc = new SampleClass();
        IControl ctrl = (IControl)sc;
        ISurface srfc = (ISurface)sc;

        // The following lines all call the same method.
        sc.Paint();
        ctrl.Paint();
        srfc.Paint();
    }
}


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

// 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 加以呼叫。 這兩種方法實作都是獨立的,而且兩者都無法直接從類別上使用。 例如:

// Call the Paint methods from Main.

SampleClass obj = new SampleClass();
//obj.Paint();  // Compiler error.

IControl c = (IControl)obj;
c.Paint();  // Calls IControl.Paint on SampleClass.

ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass. 

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

明確實作也可以用來解決兩個介面宣告不同成員但名稱相同的情況,例如屬性和方法:

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

若要實作兩個介面,類別必須為屬性 P 或方法 P (或兩者) 使用明確實作,以避免發生編譯器錯誤。 例如:

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

請參閱

參考

類別和結構 (C# 程式設計手冊)

介面 (C# 程式設計手冊)

繼承 (C# 程式設計手冊)

概念

C# 程式設計手冊