首页 文章

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

提问于
浏览
6

可能的重复:C#:接口 - 隐式和显式实现隐式与显式接口实现

你好

谁能解释一下隐式和显式接口之间的区别是什么?

谢谢!

4 回答

  • 2

    隐式接口实现是指具有相同签名的接口的方法 .

    显式接口实现是您显式声明方法所属的接口的位置 .

    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:implicit and explicit interface implementations

  • 9

    实现接口explicitlty时,只有将对象作为接口引用时,该接口上的方法才可见:

    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
    
  • 3

    显式只是意味着您指定接口,隐含意味着您不指定 .

    例如:

    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
        {
    
        }
    }
    
  • 1

    此外,如果您想知道为什么存在显式实现,那么通过简单的重载就可以实现这一点 . 那么你将不得不使用显式实现 . 一个例子是 List<T> 实现 IEnumerableIEnumerable<T> 并且都具有 GetEnumerator() 但具有不同的返回值 .

相关问题