我有一个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);
}
}
我的问题是
答案 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);
}