C# - What is the reason for “Explicitly implemented interface members are always implicitly private ?”

后端 未结 3 1873
执笔经年
执笔经年 2020-12-11 17:42

When i need to implement the interface member explicitly ,it is private.

for example :

 // when explicit implementation it is always private
  void I         


        
相关标签:
3条回答
  • 2020-12-11 18:09

    Explicitly implemented interface members aren't simply private. They're public - sort of.

    They're public in that any code which can cast the reference to the interface can call them. (If the interface itself isn't public, then I guess you could say they effectively have the same access level as the interface.)

    They don't have any specified access level because they have to be public in terms of the interface: there's no choice involved. They're not public members in the same way as normal public members of a type, but they're callable from any other assembly which can get hold of a reference and cast it to the interface type...

    The C# 3.0 specification puts it this way:

    Explicit interface member implementations have different accessibility characteristics than other members. Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public.

    0 讨论(0)
  • 2020-12-11 18:23

    Because 2 interfaces that implemented by that class explicitly can have method with the same name. That is why that method is private when accessing by class reference and public when interface.

    0 讨论(0)
  • 2020-12-11 18:23

    Because you are saying when my object is an IPointy than you can call the IPointy method draw. Otherwise no.

     public interface IPointy
    {
        void Draw();
    }
    
    public class PointyImplementer : IPointy
    {
        #region IPointy Members
    
        void IPointy.Draw()
        {
            Console.WriteLine("You have drawn");
        }
    
        #endregion
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            IPointy pi = new PointyImplementer();
    
            pi.Draw();
    
            Console.Read();
        }
    }
    

    It is a way for you to mask the interface you are implementing.

    0 讨论(0)
提交回复
热议问题