是否可以将接口实现设为私有?
不完全私有 - 接口表示一组公共方法和属性.没有办法让接口实现私有化.
你可以做的是明确实现:
public interface IFoo
{
void Bar();
}
public class FooImpl
{
void IFoo.Bar()
{
Console.WriteLine("I am somewhat private.")
}
private void Bar()
{
Console.WriteLine("I am private.")
}
}
Run Code Online (Sandbox Code Playgroud)
现在唯一的方法IFoo.Bar()是通过接口显式调用:
FooImpl f = new FooImpl();
f.Bar(); // compiler error
((IFoo)f).Bar();
Run Code Online (Sandbox Code Playgroud)