简体   繁体   English

接口上的扩展方法; 代表

[英]Extension methods on an interface; delegates

I'm trying to get around dual inheritance in C# by re-implementing one of the parent classes as an interface with extension methods. 我试图通过将父类之一重新实现为具有扩展方法的接口来解决C#中的双重继承问题。

The problem I'm encountering is that 我遇到的问题是

event EventHandler<EventArgs> Disconnecting;

public static void OnDisconnected(this AutoConnectClientBase target)
        {
            target.ClientConnectionState = ConnectionState.Disconnected;
            target.Disconnected(target, EventArgs.Empty);
        } 

Can't be called in the extension methods. 不能在扩展方法中调用。 I get: ***.Disconnecting can only appear on the left hand side of += or -= 我得到:***。断开连接只能出现在+ =或-=的左侧
While this makes perfect sense, in this case I wish it were not so. 尽管这很合理,但在这种情况下,我希望并非如此。

What I'm looking for is a workaround that will permit me to access my interface's EventHandlers in the extension code. 我正在寻找一种解决方法,该方法将允许我在扩展代码中访问接口的EventHandlers。 I'd like to keep it as simple as possible since the class I'm making into an interface is accessed by a large number of classes already and this is a change I'm reluctantly making in the first place. 我想使它尽可能的简单,因为我要在一个接口中创建的类已经被大量的类访问,而这是我最不愿意做的更改。

Not sure what the problem is here -- the code you show doesn't match the error you cite (no call to .Disconnecting . 不确定问题出在哪里-您显示的代码与您引用的错误不符(不调用.Disconnecting

public interface IInterface
{
    event EventHandler Event;
    EventHandler Handler { get; set; }
}

public class Class : IInterface
{
    public event EventHandler Event;
    public EventHandler Handler { get; set; }

}

public static class InterfaceExtensions
{
    public static void DoSomething(this IInterface i)
    {
        i.Event += (o, e) => Console.WriteLine("Event raised and handled");
        i.Handler(i, new EventArgs());
    }
}

I resolved this by doing the following: 我通过执行以下操作解决了这个问题:
Outside of the interface 界面之外

public delegate EventHandler<EventArgs> MyEventHandler(object sender, EventArgs e);

Then inside the interface 然后在界面里面

event EventHandler<EventArgs> Disconnecting;

becomes 变成

MyEventHandler Connected {get; set;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM