c#将事件的参数从另一个类传递到主类

ore*_*enk 3 c# events class winforms

我有一个主 (Form1) 类和一个处理所有串行通信 (ComPort) 的第二个类

当通过串行端口(事件)接收到新数据时,我想将其传递给 Form1 并对这些数据进行一些操作。小例子:从接收到的数据创建长字符串

表格1.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);
}
Run Code Online (Sandbox Code Playgroud)

}

串行通信.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 ?


    }  
  }
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

Form1 Form;  
Form1.addNewDataMethod(inputData.ToString());
Run Code Online (Sandbox Code Playgroud)

上面的代码会产生一个错误:use of unassigned local variable "Form"

Form1 Form1 = new Form1(); 
Form1.addNewDataMethod(inputData.ToString());
Run Code Online (Sandbox Code Playgroud)

以上将创建一个新的 Form1 实例,并且不会包含之前接收到的数据。

有什么建议 ?

Ser*_*kiy 5

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);
    }  
}
Run Code Online (Sandbox Code Playgroud)

然后在您的表单中订阅此事件。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想遵循 Microsoft 的 WinForms 编码指南,那么Action<byte[]>您应该使用EventHandler<DataReceivedEventArgs>委托而不是委托,其中 DataReceivedEventArgs类是从EventArgs.