我有一个非常简单的场景:“人”可以是公司的“客户”或“员工”。
可以使用“调用”方法通过电话调用“人”。
取决于“人”在通话内容中扮演的角色,例如新产品公告或组织变更公告,我们应该使用为“客户”角色提供的电话号码或为“员工”提供的电话号码>”角色。
总结一下情况:
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()
方法;他们只是从同一个接口(interface)继承方法。您的Both
类两次实现相同的接口(interface)。
任何可能的 Call
调用都将始终调用 IPerson.Call
;没有 IL 指令专门调用 ICustomer.Call
或 IEmployee.Call
。
您可以通过在两个子界面中显式重新定义 Call
来解决这个问题,但我强烈建议您只给它们不同的名称。
关于c# - 显式接口(interface)实现限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379838/