implementing IEnumerable and IEnumerable.GetEnu

2019-02-25 13:31发布

问题:

To implement an interface member, the corresponding member of the implementing class must be public. source: Interfaces (C# Programming Guide)

I know it works if its private, but i would like to understand why it can not be public ?

回答1:

When implemented explicitly interface methods are public by default and that's why you cannot use access modifiers.

A quote from msdn.com :

When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface (which is public by default)

source : https://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx

P.S. Difference between implicit and explicit implementation :

interface MyInterface
{
   void MyMethod();
}

class A : MyInterface  // Implicit implementation
{
   public void MyMethod () { ... }
}

class B: MyInterface   // Explicit implementation
{
   void MyInterface.MyMethod () { ... }
}