3 回答

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

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