我使用Action<T> Delegate
使类和表单之间的链接。类连接到串口,接收到的数据显示在表单中。Action<T> Delegate
在表单中封装了一个方法来显示接收到的数据。但是委托总是显示null,没有封装方法。
类代码为:
public SerialPort mySerialPort;
public Action<byte[]> DataReceived_Del; //delegate for data recieved
public string connect()
{
try
{
mySerialPort = new SerialPort("COM14");
mySerialPort.BaudRate = 115200;
mySerialPort.DataBits = 8;
mySerialPort.Parity = System.IO.Ports.Parity.None;
mySerialPort.StopBits = System.IO.Ports.StopBits.One;
mySerialPort.RtsEnable = false;
mySerialPort.DataReceived += mySerialPort_DataReceived;
mySerialPort.Open();
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message);
}
if (mySerialPort.IsOpen)
{
return "Connected";
}
else
{
return "Disconnected";
}
}
//serial port data recieved handler
public void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
//no. of data at the port
int ByteToRead = mySerialPort.BytesToRead;
//create array to store buffer data
byte[] inputData = new byte[ByteToRead];
//read the data and store
mySerialPort.Read(inputData, 0, ByteToRead);
var copy = DataReceived_Del;
if (copy != null) copy(inputData);
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message, "Data Received Event");
}
}
在我们显示数据的表单中:
public Form1()
{
InitializeComponent();
Processes newprocess = new Processes();
newprocess.DataReceived_Del += Display;
}
//Display
public void Display(byte[] inputData)
{
try
{
Invoke(new Action(() => TboxDisp.AppendText((BitConverter.ToString(inputData)))));
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message, "Display section");
}
}
DataReceived_Del
应该封装方法Display
,但它是NULL
。
我看不出发生了什么事。
你应该在构造函数之外定义newprocess,这可能会解决
Processes newprocess;
public Form1()
{
InitializeComponent();
newprocess = new Processes();
newprocess.DataReceived_Del += Display;
}
您正在使用+=添加到委托,但委托是NULL开始。我不确定那是否有效。我想试试=而不是+=。
public Form1() {
InitializeComponent();
Processes newprocess = new Processes();
newprocess.DataReceived_Del = Display;
}