這種行爲其實有一個很好的理由。考慮下面的代碼。
public interface IA
{
IA DoSomething();
}
public interface IB
{
IB DoSomething();
}
public class Test : IA, IB
{
public IA DoSomething() { return this; }
IA IA.DoSomething() { return this; }
IB IB.DoSomething() { return this; }
}
在這種情況下的Test
類必須實現的方法DoSomething
明確的至少一個,因爲它是不合法的聲明具有相同簽名兩種不同的方法。如果你要檢查IL,你會發現明確實現一個接口會自動裝飾成員名稱,以便同一個類中不存在具有相同名稱的兩個成員。爲了能夠調用上述3個不同的DoSomething
變體,您必須從正確類型的引用調用成員。這就是編譯器知道如何綁定到正確的成員。
public static void Main()
{
var test = new Test();
test.DoSomething(); // Compiler binds to the implicit implementation.
var a = (IA)test;
a.DoSomething(); // Compiler binds to the IA implementation.
var b = (IB)test;
b.DoSomething(); // Compiler binds to the IB implementation.
}