我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
。
我看不到发生了什么。。
任何帮助表示赞赏..