implementing IEnumerable<T> and IEnumerable.GetEnumerator() can not be public, why?

五迷三道 提交于 2020-01-11 09:59:13

问题


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 () { ... }
}


来源:https://stackoverflow.com/questions/31190025/implementing-ienumerablet-and-ienumerable-getenumerator-can-not-be-public-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!