3 回答

TA貢獻2011條經驗 獲得超2個贊
基本上,通過隱式接口實現,您可以訪問接口方法和屬性,就像它們是類的一部分一樣。使用顯式接口實現,您只能在將其視為該接口時訪問它們。
就何時使用另一個接口而言,有時您必須使用顯式接口實現,因為您要么具有與接口具有相同簽名的屬性/方法,要么想要實現具有相同簽名的兩個接口并具有不同的實現那些匹配的屬性/方法。
以下規則來自Brad Abrams 設計指南博客。
不要將顯式成員用作安全邊界。任何將實例投射到接口的客戶端都可以調用它們。
不要使用顯式成員來隱藏實現細節
不要使用顯式成員來近似私有接口的實現。
不要公開另一種方法來訪問允許子類重寫的任何顯式實現的成員。除非會發生沖突,否則請使用相同的方法名稱。
在布拉德(Brad)博客的評論中還提到,在對值類型使用顯式實現時涉及拳擊,因此請注意性能成本。

TA貢獻1784條經驗 獲得超9個贊
用外行的話來說,如果一個類繼承自2個或更多接口,并且這些接口碰巧具有相同的方法名,則如果您使用隱式接口實現,則該類將不知道正在實現哪種接口方法。這是您顯式實現接口時的場景之一。
隱式接口實現
public class MyClass : InterfaceOne, InterfaceTwo
{
public void InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
顯式接口實現
public class MyClass : InterfaceOne, InterfaceTwo
{
void InterfaceOne.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
void InterfaceTwo.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
- 3 回答
- 0 關注
- 535 瀏覽
添加回答
舉報