您是否有理由无法在方法或界面中定义访问修饰符?

Bas*_*mme 5 c# interface access-modifiers

方法可见性的责任归结为实现接口的类.

public interface IMyInterface
{
  bool GetMyInfo(string request);
}
Run Code Online (Sandbox Code Playgroud)

在方法GetMyInfo()生成以下错误之前,在C#set访问修饰符public,private或protected中:修饰符'private'对此项无效.

您是否有理由无法在方法或界面中定义访问修饰符?

(问题已经在法语中提到了这里)

Gra*_*meF 14

该接口定义了一个对象和调用其成员的客户端之间的契约.任何其他对象都无法访问私有方法,因此将其添加到接口没有意义.由于这个原因,接口的所有成员都被视为公共成员.


Fre*_*örk 10

可以真正使实现类的方法私有的,如果你让一个明确的接口实现:

public interface IMyInterface
{
    bool GetMyInfo(string request);
}

public class MyClass : IMyInterface
{
    public void SomePublicMethod() { }

    bool IMyInterface.GetMyInfo(string request)
    {
        // implementation goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法意味着GetMyInfo不会成为公共接口的一部分MyClass.只能通过将MyClass实例强制转换为以下内容来访问它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");
Run Code Online (Sandbox Code Playgroud)

因此,在界面的上下文中,其所有成员都将是公共的.它们可以从实现类的公共接口隐藏,但总是有可能对实例进行类型转换并以这种方式访问​​成员.