C# 使用泛型类型创建事件

C# 使用泛型类型创建事件,c#,events,C#,Events,我想要编写一个类,通过将类型序列化为Byte[]并在事件中将Byte[]反序列化回对象,来发送对象 public interface ISource { event EventHandler<T> myevent; void Send<T>(T dataToSend); } 公共接口源 { 事件处理程序myevent; 无效发送(T数据发送); } 事件代码行在编译器中不起作用,但这正是我所需要的 实施示例: publi

我想要编写一个类,通过将类型序列化为Byte[]并在事件中将Byte[]反序列化回对象,来发送对象

public interface ISource
    {
        event EventHandler<T> myevent;
        void Send<T>(T dataToSend);
    }
公共接口源
{
事件处理程序myevent;
无效发送(T数据发送);
}
事件代码行在编译器中不起作用,但这正是我所需要的

实施示例:

public class Source : ISource
{
    ISerialPort _port;

    public Source (ISerialPort port)
    {
        _port = port;
    }

    public event EventHandler<T> myevent;

    public void Send<T>(T dataToSend)
    {
        //Converts type to an Byte[] with Serialisation
        //And send the Data
        _port.Send(ConvertedByteArray);
    }
}
公共类来源:ISource
{
ISerialPort\u端口;
公共源(iSeries端口)
{
_端口=端口;
}
公共事件事件处理程序;
公共无效发送(T数据发送)
{
//通过序列化将类型转换为字节[]
//并发送数据
_发送端口(通过tearray转换);
}
}
发送部分工作正常,因为我可以在 调用Send方法

obj.Send<List<String>>(myList); 
obj.Send(myList);
现在我想用一个事件创建另一个方向(Byte[]->T)

因此,我在订阅源类中的事件时指定EventDataType的值

有一个优雅的解决方案吗

我不想指定“public class”这样的类型 因为我希望类可以接收和发送不同的obj/类型

问候 rubiktubik

您必须在 接口声明和类声明

interface ISource<T> where T : EventArgs
{
    event EventHandler<T> MyEvent;
    void Send<G>(G dataToSend);
}
public class Source<T> : ISource<T> where T : EventArgs
{

    public event EventHandler<T> MyEvent;

    public void Send<T>(T dataToSend)
    {
        throw new NotImplementedException();
    }
}
接口源,其中T:EventArgs
{
事件处理程序MyEvent;
无效发送(G数据发送);
}
公共类源:ISource,其中T:EventArgs
{
公共事件事件处理程序;
公共无效发送(T数据发送)
{
抛出新的NotImplementedException();
}
}
EventArgs
创建一个派生类以传入