这称为显式接口实现。主要用于消除在不同接口中存在的具有相同名称的成员的歧义,这也需要不同的实现。
认为你有
interface ISomething1{ void DoSomething();}interface ISomething2{ void DoSomething();}class MyClass : ISomething1, ISomething2{ void ISomething1.DoSomething() { //Do something } void ISomething2.DoSomething() { //Do something else }}没有Explicit接口实现,您将无法
DoSomething为我们实现的两个接口提供不同的实现。
如果要实现某个接口,并且想在客户端中隐藏它(在某种程度上),则可以使用显式实现。
Array类
IList显式实现接口,这就是隐藏的方式
IList.Add,
IList.Remove等等。不过,如果将其强制转换为
IList类型,则可以调用它。但是在这种情况下,您最终将获得异常。
通过显式实现实现的成员在类实例中不可见(即使在类内部)。您需要通过接口实例访问它。
MyClass c = new MyClass();c.DoSomething();//This won't compileISomething1 s1 = c;s1.DoSomething();//Calls ISomething1's version of DoSomethingISomething2 s2 = c;s2.DoSomething();//Calls ISomething2's version of DoSomething



