Is there a reason you can not define the access modifier on a method or in an interface?

后端 未结 5 1995
悲哀的现实
悲哀的现实 2020-12-21 00:23

The responsibility of the visibility of a method is relegated to the class that implements the interface.

public interface IMyInterface
{
  bool GetMyInfo(st         


        
相关标签:
5条回答
  • 2020-12-21 00:55

    All of the methods of an interface must have the same access level - so that the caller may use all of them. However interfaces can also be internal (or as nested interface private).

    If you need different access levels use a distinct interface.

    0 讨论(0)
  • 2020-12-21 00:58

    A private definition in the interface would:

    1. provide no benefit to the user of the interface (it is private after all)
    2. constrain the implementing class to have to implement the method or property
    3. muddy the conceptual nature of the interface with implementational detail
    4. be like an abstract class with a private method (which is not allowed)
    0 讨论(0)
  • 2020-12-21 01:02

    In terms of OO - encapsulation is all about data hiding. That means whatever goes on inside a class is up to the class implementation. Which means it would be useless to contractually enforce private members.

    However, the reason one uses interfaces is because you want to ensure a class adheres to a specific contract and exposes several public members in a consistent way.

    0 讨论(0)
  • 2020-12-21 01:07

    The interface defines a contract between an object and clients that call its members. A private method cannot be accessed by any other objects so it doesn't make sense to add it to the interface. All members of an interface are considered public for this reason.

    0 讨论(0)
  • 2020-12-21 01:15

    You can actually make the method private in the implementing class, if you make an explicit interface implementation:

    public interface IMyInterface
    {
        bool GetMyInfo(string request);
    }
    
    public class MyClass : IMyInterface
    {
        public void SomePublicMethod() { }
    
        bool IMyInterface.GetMyInfo(string request)
        {
            // implementation goes here
        }
    }
    

    This approach means that GetMyInfo will not be part of the public interface of MyClass. It can be accessed only by casting a MyClass instance to IMyInterface:

    MyClass instance = new MyClass();
    
    // this does not compile
    bool result = instance.GetMyInfo("some request"); 
    
    // this works well on the other hand
    bool result = ((IMyInterface)instance).GetMyInfo("some request");
    

    So, in the context of the interface, all its members will be public. They can be hidden from the public interface of an implementing class, but there is always the possibility to make a type cast to the instance and access the members that way.

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