为事件订阅通用方法

时间:2015-04-24 06:27:01

标签: c# events

我希望事件发生后运行的方法是:

protected virtual void RunThisMethod<T>(object sender, CustomEventArgs<T> e)
        where T : IMyInterface
    {
        //Do something
    }

当我订阅活动时:

eventSource.SomeEvent += RunThisMethod;

我收到了错误。

The type arguments for method 'RunThisMethod<T>(object, CustomEventArgs<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

如何在订阅时提供IMyInterface? 还是我犯了一些根本性的错误?

编辑:该事件定义为:

event EventHandler<CustomEventArgs> SomeEvent ;

1 个答案:

答案 0 :(得分:0)

您需要确保正确声明事件类型。您需要指定CustomEventArgs&lt; T>不只是CustomEventArgs。试试这个:

public class CustomEventArgs<T> : EventArgs
{
    public T CustomArgs { get; set; }
}

public class Example<T>
{
    public Example()
    {
        this.MyEvent += this.Handler;
    }

    public event EventHandler<CustomEventArgs<T>> MyEvent;

    private void Handler(object sender, CustomEventArgs<T> args)
    {

    }
}