“实现接口显式”类中的方法调用

时间:2012-07-05 10:55:46

标签: c# .net inheritance

我想了解基于下面描述的上下文/场景,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
    }
}

2 个答案:

答案 0 :(得分:1)

void ITestService.Operation1()
{
    ((ITestService)this).Operation2();
}

至于你的第二个问题:

接口的所有成员都是公开的。因此,实施也将公开。

答案 1 :(得分:1)

第二个问题

  

testService1.Operation1(); // =>作品:为什么这是可能的,   特别是自操作1()和操作2()将被视为   私人?

由于界面中的功能是公共的,您可以调用它们。此外,您已明确实现了接口方法,您无法针对类对象调用它。例如

TestService ts = new TestService();
ts.Operation1();// this would cause an error

您可能会看到:Explicit Interface Implementation (C# Programming Guide)