从通用 class 调用通用事件处理程序

Call Generic EventHandler from generic class

我是以下实现的派系和问题,编译器抛出错误 "delegate has invalid argument error by compiler",检查下面的代码

public class MessageArgument<T> : EventArgs
{
    public T Message { get;  set; }

    public MessageArgument(T message)
    {
        Message = message;
    }
}

public class Publisher<T>
{
    //Defined datapublisher event
    public event EventHandler<MessageArgument<T>> DataPublisher;

    public virtual void OnDataPublisher<T>(MessageArgument<T> args)
    {
        var handler = DataPublisher;
        if (handler != null)
         //delegate has invalid argument error by compiler
            handler(this, args);
    }

    public void PublishData<T>()
    {
       //also facing issue with creating of generic type instace
        MessageArgument<T> message = (MessageArgument<T>)Activator.CreateInstance(typeof(MessageArgument<T>), new object[] { 10 }); 
        OnDataPublisher(message);
    }
}

您有一个泛型 class,这意味着您不需要对方法进行泛型约束,因为它们被视为单独的泛型类型。从您的方法中删除 <T> 约束,它应该可以工作:

public class Publisher<T>
{
    //Defined datapublisher event
    public event EventHandler<MessageArgument<T>> DataPublisher;

    public virtual void OnDataPublisher(MessageArgument<T> args)
    {
        var handler = DataPublisher;
        if (handler != null)
         //delegate has invalid argument error by compiler
            handler(this, args);
    }

    public void PublishData()
    {
        MessageArgument<T> message = (MessageArgument<T>)Activator.CreateInstance(typeof(MessageArgument<T>), new object[] { 10 }); 
        OnDataPublisher(message);
    }
}