C# 是否将SerialPort.ReadExisting()方法中的数据存储在变量中?

C# 是否将SerialPort.ReadExisting()方法中的数据存储在变量中?,c#,serial-port,C#,Serial Port,我想从连接到串行端口的设备读取信息。我以前使用表单(下面的代码)完成了这项工作,但我尝试在没有表单的情况下完成这项工作,只是将信息存储到字符串数组中 与表单一起使用的代码: private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string line = port.ReadExisting(

我想从连接到串行端口的设备读取信息。我以前使用表单(下面的代码)完成了这项工作,但我尝试在没有表单的情况下完成这项工作,只是将信息存储到字符串数组中

与表单一起使用的代码:

private void serialPort1_DataReceived(object sender,  System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                string line = port.ReadExisting();              
                this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
            }

        private delegate void LineReceivedEvent(string line);
        private void LineReceived(string line)
        {
            textBox3.AppendText(line);
        }
我在没有表单的情况下走了多远(DA方法允许在程序中存储变量)。最后一行出现以下错误
无法将类型“string”隐式转换为“System.IO.Ports.SerialDataReceivedEventHandler”

protected override void SolveInstance(IGH_DataAccess DA)
  {
    string selectedportname;
    DA.GetData(1, ref selectedportname);
    int selectedbaudrate;
    DA.GetData(2, ref selectedbaudrate);
    bool connecttodevice;
    DA.GetData(3, ref connecttodevice);
    bool sendtoprint;
    DA.GetData(3, ref sendtoprint);


    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
    port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
    port.Open();             //Open the port
    port.DataReceived += port.ReadExisting();                                             

  }

假设
ReadExisting
是具有正确参数的方法:

//port.DataReceived += port.ReadExisting();   
  port.DataReceived += port.ReadExisting;   
但是错误表明它正在返回一个“字符串”,因此这里还有更多问题需要解决

编辑: 看起来应该是:

  port.DataReceived += this.serialPort1_DataReceived;   

假设
ReadExisting
是具有正确参数的方法:

//port.DataReceived += port.ReadExisting();   
  port.DataReceived += port.ReadExisting;   
但是错误表明它正在返回一个“字符串”,因此这里还有更多问题需要解决

编辑: 看起来应该是:

  port.DataReceived += this.serialPort1_DataReceived;   

即使您没有使用表单,您仍然需要为代表分配适当的签名来处理DataReceived事件发布
LineReceived
ReadExisting
@HenkHolterman的代码(至少是标题),我在表单使用的代码中添加了LineReceived。ReadExisting是此方法的一部分:即使您没有使用表单,您仍然需要为代理分配适当的签名来处理DataReceived事件。在
LineReceived
ReadExisting
@Henkholtman的代码(至少是标题)后,我在表单使用的代码中添加了LineReceived。ReadExisting是这个方法的一部分:thx Henk,这只是在我使用serialPort1_DataReceived方法的情况下,但我尝试不使用它,而是在SolveInstance方法中完成所有操作。这不可能吗?这里的问题越来越复杂了。您需要一个具有类似签名的方法
(object sender,SerialDataReceivedEventArgs e)
或lambda来附加到接收到的事件。thx Henk,这仅在我使用serialPort1\u DataReceived方法的情况下,但我尝试不使用它,而是在SolveInstance方法内完成所有操作。这不可能吗?这里的问题越来越复杂了。您需要具有类似签名的方法
(对象发送方,SerialDataReceivedEventArgs e)
或lambda来附加到接收到的事件。