将事件的参数从另一个类传递到主类
本文关键字:另一个 事件 参数 | 更新日期: 2023-09-27 18:02:20
我有一个主(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 ?
}
}
I Tried the following:
Form1 Form;
Form1.addNewDataMethod(inputData.ToString());
上面的代码会产生一个错误:使用未赋值的局部变量"Form"
Form1 Form1 = new Form1();
Form1.addNewDataMethod(inputData.ToString());
上面的代码将创建一个新的Form1实例,并且不包含之前接收到的数据。
有什么建议吗
在SerialCommunication
类中创建一个事件,该事件将在数据到达时引发:
public partial class SerialCommunicationPort
{
public event Action<byte[]> DataReceived;
public void ComPortBufferRead(object sender, SerialDataReceivedEventArgs e)
{
byte[] inputData = new byte[ComPort.BytesToRead];
ComPort.Read(inputData, 0, ComPort.BytesToRead);
if (DataReceived != null)
DataReceived(inputData);
}
}
然后在您的表单中订阅此事件。
public partial class Form1 : Form
{
SerialCommunication serialCommunication;
public Form1()
{
InitializeComponent();
serialCommunication = new SerialCommunication();
serialCommunication.DataReceived += SerialCommunication_DataReceived;
}
private void SerialCommunication_DataReceived(byte[] data)
{
// get string from byte array
// and call addNewDataMethod
}
}
如果你想遵循微软的编码指南的WinForms,那么代替Action<byte[]>
委托,你应该使用EventHandler<DataReceivedEventArgs>
委托,其中DataReceivedEventArgs
是从EventArgs
继承的类。
最好的方法可能是使用事件。定义一个EventArgs参数的事件,该参数接受一个字符串。在Form1中订阅事件,在串行通信类中触发事件,将您想要的字符串传递给eventargs。
你想要的方式应该也能工作,但是像这样:
Form1 Form = new Form1();
Form.Show(); // to display it...
/// to other stuff...
Form.addNewDataMethod(inputData); // call the method on the INSTANCE which you opened!
与方法的用法类似,您可以在Form1中定义一个属性:
private string _myString = "";
public string MyString {
private get {
}
set {
string _myString= value;
// to with the string what you want
}
}
然后类似于方法调用使用
Form.MyString = "abc";
希望这有帮助!