gpt4 book ai didi

c# - 从通用类调用通用事件处理程序

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:14 24 4
gpt4 key购买 nike

我是派系,下面的实现有问题,编译器抛出错误“委托(delegate)有编译器的无效参数错误”,检查下面的代码

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

最佳答案

你有一个泛型类,这意味着你不需要对方法进行泛型约束,因为它们被视为一个单独的泛型类型。删除 <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);
}
}

关于c# - 从通用类调用通用事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com