Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用不同方法名称的接口实现_C#_.net_Oop - Fatal编程技术网

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

C# 使用不同方法名称的接口实现,c#,.net,oop,C#,.net,Oop,我有这个界面: public interface INameScope { void Register(string name, object scopedElement); object Find(string name); void Unregister(string name); } 但是我希望我的实现有不同的方法名称。我的实现已经有了另一个含义的Register方法 是否有一种方法可以使实现的方法具有“RegisterName”、“FindName”或“Unre

我有这个界面:

public interface INameScope
{
    void Register(string name, object scopedElement);
    object Find(string name);
    void Unregister(string name);
}
但是我希望我的实现有不同的方法名称。我的实现已经有了另一个含义的Register方法


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

不完全相同,但您可以使用:

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

SomeScope x = new SomeScope(...);
INameScope y = x;
x.Register(...); // Does one thing
y.Register(...); // Does something entirely different

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

interface IMyInterface {
    void Register(string name);
}

class MyImplementation {
    public void RegisterName(string name) {
        // Wrong Register
    }
    public void RegisterName(string name) {
        // Right Register
    }
}
桥接类将
MyImplementation
IMyInterface
进行“解耦”,允许您独立更改方法和属性的名称:

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

当对桥接器的某一侧进行更改时,您需要在桥接器中进行相应的更改以恢复业务。

为什么不更改接口?因为。。。啊,我的错。不清楚您是否无法根据问题调整界面。我今天在C#中遇到了这个问题。让我抓狂的是,Visual Basic(我在以前的工作中使用过)中提供了这一功能:
公共函数MyCustomRegisterMethod()在mescope.Register中实现。接受的答案对我来说不够好,因为功能取决于我是将其视为接口还是具体类型。类似于阴影:是的,我知道你的意思。也许应该有一个具有名称范围(关联)的宿主类,并公开其方法,如public RegisterName(…){namescope.Register(…)}。那么,这更像是一个设计问题?@SuperJMN:是的,这很有意义——除了你不能使用你现有的类来处理任何需要
INameScope
的事情。这一点很好,Jon。但这对我来说仍然是个大麻烦。接口名称强制实现者保留这些名称,不管它们是否有意义……好吧,但正如您所看到的,使用桥接器,您不会更改被调用方法的名称。在接口中称为“寄存器”,与网桥中的名称相同。我想要的是用一个不同的名称来实现它。@SuperJMN桥让
MyImplementation
假装它实现了
IMyInterface
,而不是实际实现它。桥接器使用匹配的名称实现接口以保持C#高兴,但实现的“有效负载”逻辑来自
MyImplementation
class。桥接类只是转发调用,而
MyImplementation
完成所有工作并保持所有状态。
class MyBridge : IMyInterface {
    private readonly MyImplementation impl;
    public MyBridge(MyImplementation impl) {
        this.impl = impl;
    }
    public void Register(string name) {
        impl.RegisterName();
    }
}