如何将事件传播和自定义到其他类?

时间:2012-03-15 11:18:39

标签: c# events event-handling serial-port

我有一个SerialPortWrapper类来处理System.IO.Ports.SerialPort,其中包含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的类?
  • 如何制作与他们正在进行的课程相关的自定义事件?

1 个答案:

答案 0 :(得分:1)

你实际上并没有提起这件事。

删除此行:

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