开发者

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.

The problem I'm encountering is t开发者_StackOverflow社区hat

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. 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.

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;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜