如何向其他类传播和自定义事件



我有一个处理System.IO.Ports.SerialPort的SerialPortWrapper类,其中包括OnSerialDataRecevied事件处理程序。以下是该类的概要,它是有效的:

public class SerialPortWrapper : ISerialPortWrapper
{
    public event SerialDataReceivedEventHandler DataReceviedHandler;    
    private readonly SerialPort _serialPort;
    public SerialPortWrapper()
    {
        this._serialPort = new SerialPort
        {
            // configure SerialPort
        };
        this._serialPort.DataReceived += DataReceviedHandler;
        this._serialPort.DataReceived += OnSerialDataRecevied;
    }
    public void Write(byte[] bytes, int offset, int count)
    {
        this._serialPort.Write(bytes, offset, count);
    }
    public void OnSerialDataRecevied(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        var bytes = new UTF8Encoding().GetBytes(sp.ReadExisting());
    }
}

我还有一个使用SerialPortWrapper的类。当OnSerialDataRecevied启动时,我希望在这个类中启动一个事件。优选地,该事件对象将包含SecurityPanel将关注的自定义数据,而不是SerialPort数据

您可以在下面的代码中看到,我试图添加SecurityDataRecevied作为SerialPortWrapper的DataReceviedHandler的处理程序,但这不起作用。

public class SecurityPanel : ISecurityPanel
{
    private readonly ISerialPortWrapper _serialPortWrapper;
    public SecurityPanel(ISerialPortWrapper serialPortWrapper)
    {
        _serialPortWrapper = serialPortWrapper;
        _serialPortWrapper.DataReceviedHandler += SecurityDataRecevied;
    }
    private void SecurityDataRecevied(object sender, SerialDataReceivedEventArgs e)
    {
        // this doens't fire. Prefereably it would have a custom EventArgs object, 
        // rather than SerialDataReceivedEventArgs 
    }
    public byte SendMessage(Message message)
    {
        // get bytes from message and send them to the SerialPort
        _serialPortWrapper.Write(bytes, 0, bytes.Length);            
    }
}

我的问题是

  • 如何将事件传播到使用SerialPortWrapper的类
  • 如何使这些自定义事件与它们所在的类相关

您实际上并没有引发事件。

删除此行:

this._serialPort.DataReceived += DataReceviedHandler;

并修改功能:

public void OnSerialDataRecevied(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    var bytes = new UTF8Encoding().GetBytes(sp.ReadExisting());
    if(DataReceivedHandler != null)
        DataReceivedHandler(sender, e);
}

相关内容

  • 没有找到相关文章

最新更新