隐式<>显式接口[重复]

|                                                                                                                   这个问题已经在这里有了答案:                                                      
已邀请:
隐式接口实现是您拥有具有相同接口签名的方法的地方。 显式接口实现是在其中显式声明该方法所属的接口的地方。
interface I1
{
    void implicitExample();
}

interface I2
{
    void explicitExample();
}


class C : I1, I2
{
    void implicitExample()
    {
        Console.WriteLine(\"I1.implicitExample()\");
    }


    void I2.explicitExample()
    {
        Console.WriteLine(\"I2.explicitExample()\");
    }
}
MSDN:隐式和显式接口实现     
显式实现接口时,仅当将对象引用为接口时,该接口上的方法才可见:
public interface IFoo
{
   void Bar();
}

public interface IWhatever
{
   void Method();
}

public class MyClass : IFoo, IWhatever
{
   public void IFoo.Bar() //Explicit implementation
   {

   }

   public void Method() //standard implementation
   {

   }
}
如果在代码中的某处,您可以引用该对象:
MyClass mc = new MyClass();
mc.Bar(); //will not compile

IFoo mc = new MyClass();
mc.Bar(); //will compile
对于标准实现,引用对象并不重要:
MyClass mc = new MyClass();
mc.Method(); //compiles just fine
    
显式仅表示您指定了接口,隐式表示未指定接口。 例如:
interface A
{
  void A();
}

interface B
{
  void A();
}

class Imp : A
{
    public void A() // Implicit interface implementation
    {

    }
}

class Imp2 : A, B
{
    public void A.A() // Explicit interface implementation
    {

    }

    public void B.A() // Explicit interface implementation
    {

    }
}
    
另外,如果您想知道为什么显式实现存在,那是因为您可以通过多个接口实现相同的方法(名称和签名)。那么如果您需要不同的功能,或者只是返回类型不同,则无法通过简单的重载来实现。那么您将不得不使用显式实现。一个示例是
List<T>
实现
IEnumerable
IEnumerable<T>
都具有
GetEnumerator()
,但返回值不同。     

要回复问题请先登录注册