微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 显式接口实现限制

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

可以通过电话使用“呼叫”方法呼叫“人”.

取决于“人”在呼叫的上下文中扮演的角色,例如新产品的公告或组织变更的公告,我们应该使用为“客户”角色提供的电话号码或为“员工”角色提供的电话号码.

以下是对情况的总结:

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
    }
}

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

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()'

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

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

在此先感谢您的帮助.

解决方法

你的目标没有意义.

ICustomer和IEmployee都没有定义Call()方法;他们只是从同一个接口继承该方法.您的Both类两次实现相同的接口.
任何可能的呼叫呼叫将始终呼叫IPerson.Call;没有专门调用ICustomer.Call或IEmployee.Call的IL指令.

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

原文地址:https://www.jb51.cc/csharp/91924.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐