【发布时间】:2014-05-07 10:00:22
【问题描述】:
我有一个主 (Form1) 类和一个处理所有串行通信 (ComPort) 的第二类
当通过串行端口(事件)接收到新数据时,我想将其传递给 Form1 并对这些数据进行一些操作。 小例子:根据接收到的数据创建长字符串
Form1.cs
public partial class Form1 : Form
{
//Creating instance of SerialCommunication.
....
....
string receivedString = ""; //Here I will store all data
public void addNewDataMethod(string newDataFromSerial)
{
receivedString = receivedString + newDataFromSerial;
MessageBox.Show(receivedString);
}
}
SerialCommunication.cs
public partial class SerialCommunicationPort
{
constructor()
{
.... //open serial port with the relevant parameters
ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPortBufferRead);//Create Handler
}
public void ComPortBufferRead(object sender, SerialDataReceivedEventArgs e)
{
//create array to store buffer data
byte[] inputData = new byte[ComPort.BytesToRead];
//read the data from buffer
ComPort.Read(inputData, 0, ComPort.BytesToRead);
//***** What should I write here in order to pass "inputData" to Form1.addNewDataMethod ?
}
}
我尝试了以下方法:
Form1 Form;
Form1.addNewDataMethod(inputData.ToString());
以上代码会产生错误:use of unassigned local variable "Form"
Form1 Form1 = new Form1();
Form1.addNewDataMethod(inputData.ToString());
上面会创建一个新的Form1实例,并且不会包含之前接收到的数据。
有什么建议吗?
【问题讨论】: