转发EventHandlers

时间:2017-03-30 09:13:07

标签: c# interface event-handling

我有一个注册为EventHandler的方法:

handler.Actiontriggered += LocalMethod;

现在我想用接口替换处理程序。我最终得到了类似的东西:

public interface IHandler
{
  event EventHandler<EventArgs> Actiontriggered;
}

并实施为

public class SpecificHandler : IHandler
{
    ....
    public event EventHandler<EventArgs> Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}

现在问题是我收到一个错误,EventHandler<EventArgs>无法隐式转换为特定于处理程序的类型。

Cannot implicitly convert type 'System.EventHandler<System.EventArgs>' to 'Handler.ActiontriggeredEventHandler'

因为这在原始的直接赋值中起作用:为了使用该接口也可以重写什么?

1 个答案:

答案 0 :(得分:1)

ActionTriggered类型中的handler事件声明为

public class Handler
{
    public event EventHandler<EventArgs> Actiontriggered;
}

但是作为

public class Handler
{
    public delegate void ActionTriggered (object sender, EventArgs e);
    public event Actiontriggered Actiontriggered;
}

因此您需要将界面更改为:

public interface IHandler
{
     event Handler.Actiontriggered Actiontriggered;
}

和相应的实施班:

public class SpecificHandler : IHandler
{
    ....
    public event Handler.Actiontriggered Actiontriggered
    {
        add
        {
            this.handler.Actiontriggered+= value; // handler is the same as in the snippet above
        }

        remove
        {
            this.handler.Actiontriggered-= value;
        }
    }
}

虽然Handler.Actiontriggered相同签名作为EventHandler<EventArgs>的委托类型,但它们不是同一类型,因此编译错误