使用不同方法名称的接口实现

Sup*_*JMN 5 .net c# oop

我有这个界面:

public interface INameScope
{
    void Register(string name, object scopedElement);
    object Find(string name);
    void Unregister(string name);
}
Run Code Online (Sandbox Code Playgroud)

但我希望我的实现具有不同的方法名称.我的实现已经有了一个具有另一种含义的Register方法.

是不是有一种方法可以使实现的方法具有"RegisterName","FindName"或"UnregisterName"等名称,而不必使用相同的名称?

Jon*_*eet 8

不完全,但您可以使用显式接口实现:

public class SomeScope : INameScope
{
    void INameScope.Register(string name, object scopedElement)
    {
        RegisterName(name, scopedElement);
    }

    public void Register(...)
    {
        // Does something different
    }

    public void RegisterName(...)
    {
        // ...
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

如果您现有的Register方法具有相似的参数,我会非常谨慎- 虽然编译器会对此感到满意,但您应该问自己,阅读代码的人有多清楚:

SomeScope x = new SomeScope(...);
INameScope y = x;
x.Register(...); // Does one thing
y.Register(...); // Does something entirely different
Run Code Online (Sandbox Code Playgroud)


das*_*ght 5

方法实现与它们实现的接口方法的绑定是通过方法签名完成的,即名称和参数列表.实现具有方法的接口的类Register必须具有Register具有相同签名的方法.虽然C#允许您使用不同的Register方法作为显式实现,但在这种情况下,更好的方法是使用Bridge Pattern,它允许您将接口"连接"到具有不匹配方法签名的实现:

interface IMyInterface {
    void Register(string name);
}

class MyImplementation {
    public void RegisterName(string name) {
        // Wrong Register
    }
    public void RegisterName(string name) {
        // Right Register
    }
}
Run Code Online (Sandbox Code Playgroud)

桥级"解耦" MyImplementationIMyInterface,让你改变的独立的方法和属性的名称:

class MyBridge : IMyInterface {
    private readonly MyImplementation impl;
    public MyBridge(MyImplementation impl) {
        this.impl = impl;
    }
    public void Register(string name) {
        impl.RegisterName();
    }
}
Run Code Online (Sandbox Code Playgroud)

当对桥的一侧进行更改时,您需要在桥中进行相应的更改以重新开始工作.