c# - 显式接口(interface)实现限制

标签 c# interface explicit-interface

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

可以使用“调用”方法通过电话调用“”。

取决于“”在通话内容中扮演的角色,例如新产品公告或组织变更公告,我们应该使用为“客户”角色提供的电话号码或为“员工”提供的电话号码>”角色。

总结一下情况:

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# 中实现,或者我是否必须找到另一种设计?

如果是这样,您有什么建议?

预先感谢您的帮助。

最佳答案

你的目标没有意义。

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

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

关于c# - 显式接口(interface)实现限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379838/

相关文章:

c# - 'x'中的类型 'x.cs'与导入的类型 'x'冲突

c# - 将未初始化的参数传递给方法时的 ref 关键字

c# - autofac - 在多模块应用程序中的正确使用

java - 是否可以使用 hibernate 注释持久化 List<E> ,其中 E 是一个接口(interface)?

c# - ffmpeg 无法识别

java - 为一组具有相同方法但不实现相同接口(interface)的类编写通用代码的惯用方法是什么?

delphi - TObject 对于在对象销毁时清除接口(interface)字段提供什么保证?

c# - C# 中具有显式接口(interface)的对象初始值设定项

pointers - 通过类型/种类/等级以外的方式区分 Fortran 中的泛型

c# - 可以在显式接口(interface)实现中引用同名隐式属性吗?