如何动态更改事件处理程序回调

时间:2012-01-11 08:53:07

标签: c# .net delegates callback serial-port

我有一个串口通信类,里面有以下代码(其中只显示相关部分):

public Form1 m_parent;
private delegate void ProcessPacketDelegate(byte[] packet);
public SerialPort comPort = new SerialPort();

//Constructor code
....setting baudrate, portname etc.
... setting m_parent as the main form
...setting other things

//add an event handler
comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
//constructor code end

void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
        int bytes = comPort.BytesToRead;
        byte[] comBuffer = new byte[bytes];
        comPort.Read(comBuffer, 0, bytes);
        comPort.DiscardInBuffer();
        m_parent.Invoke(new ProcessPacketDelegate(m_parent.ProcessPacket), comBuffer);
}

我从我的主窗体中实例化这个类,该地址存储在m_parent中。主窗体有一个名为ProcessPacket的方法,它处理传入的数据包。到目前为止一切都很好。

现在,我想处理2个串口,所以我需要2个这个类的实例。但是,我不希望它们使用可能导致数据包冲突的相同ProcessPacket方法。我想修改串口通信类,使得在构造函数或getsets中我动态设置回调方法,因此实例#1将调用m_parentProcessPacket_A,实例#2将调用m_parentProcessPacket_B。不幸的是,这似乎超出了我的.NET技能,所以任何帮助都会很棒! 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在构造函数中定义变量并使用它。

if(condition)
   handler =  comPort_DataReceived;
else
   handler =  comPort_SomeElseMethod;

然后绑定此

comPort.DataReceived += handler

答案 1 :(得分:0)

有这样的构造函数:

YourClass(ProcessPacketDelegate process_packet)
{
    // ...
    this.process_packet = process_packet;
}

在你的班上,还要:

ProcessPacketDelegate process_packet;

然后在comPort_DataReceived做:

m_parent.Invoke(this.process_packet, comBuffer);

在您实例化课程时的主要表单中:

instance1 = new YourClass(new ProcessPacketDelegate(this.ProcessPacket_A));
instance2 = new YourClass(new ProcessPacketDelegate(this.ProcessPacket_B));