我想根据下面描述的上下文/场景来了解在 C# 中显式实现接口的含义。可以说我有以下界面:
public interface ITestService
{
void Operation1();
void Operation2();
}
假设我显式地实现了接口,如下所示,是否可以使用任何方式从 Operation1() 调用 Operation2()?
public sealed class TestService : ITestService
{
public TestService(){}
void ITestService.Operation1()
{
// HOW WOULD ONE SUCCESSFULLY INVOKE Operation2() FROM HERE. Like:
Operation2();
}
void ITestService.Operation2()
{
}
}
发生什么不同(在包装下)以允许下面声明不同的 testService1 和 testService2 表现不同?
static class Program
{
static void Main(string[] args)
{
ITestService testService1 = new TestService();
testService1.Operation1(); // => Works: WHY IS THIS POSSIBLE, ESPECIALLY SINCE Operation1() AND Operation2() WOULD BE *DEEMED* private?
// *DEEMED* since access modifiers on functions are not permitted in an interface
// while ...
TestService testService2 = new TestService();
testService2.Operation1(); //! Fails: As expected
}
}