如果 類別 實作包含具有相同簽章成員的兩個介面,則在 類別上實作該成員會導致這兩個介面使用該成員做為其實作。 在下列範例中,所有呼叫 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
方法,可以是公用方法,或做為明確的介面實作。