显式接口实现限制

Pra*_*eek 6 c# interface explicit-interface

我有一个非常简单的场景:" "可以是公司的" 客户 "或" 员工 ".

A" ",可以通过电话与"被称为呼叫 "的方法.

根据" "在通话环境中扮演的角色,例如新产品的公告或组织变更的公告,我们应该使用为" 客户 "角色提供的电话号码或提供的电话号码为" 员工 "角色.

以下是对情况的总结:

interface IPerson
{
    void Call();
}

interface ICustomer : IPerson
{
}

interface IEmployee : IPerson
{
}

class Both : ICustomer, IEmployee
{
    void ICustomer.Call()
    {
        // Call to external phone number
    }

    void IEmployee.Call()
    {
        // Call to internal phone number
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码不能编译并产生错误:

error CS0539: 'ICustomer.Call' in explicit interface declaration is not a member of interface
error CS0539: 'IEmployee.Call' in explicit interface declaration is not a member of interface
error CS0535: 'Both' does not implement interface member 'IPerson.Call()'
Run Code Online (Sandbox Code Playgroud)

这种情况是否有机会以不同的方式在C#中实现,还是我必须找到另一种设计?

如果是这样,你建议用什么替代品?

在此先感谢您的帮助.

SLa*_*aks 9

你的目标没有意义.

既没有ICustomer也没有IEmployee定义Call()方法; 他们只是从同一个接口继承该方法.您的Both类实现了两次相同的接口.
任何可能的Call电话总是会打电话IPerson.Call; 没有特别要求的IL指令ICustomer.CallIEmployee.Call.

您可以通过Call在两个子接口中显式重新定义来解决这个问题,但我强烈建议您只给它们不同的名称.