NullReferenceException:对象引用未设置为SerialPort.ReadLine()方法上的对象实例

时间:2012-10-14 19:33:16

标签: c# serial-port grasshopper

运行下面的代码时,我得到以下NullReferenceException。我错过了什么?

 System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=Silkworm
  StackTrace:
       at UnhandledExceptionLogger.UnhandledDomainException(Object sender, UnhandledExceptionEventArgs args)

代码:

   //Fields
            List<string> myReceivedLines;

            //subscriber method for the port.DataReceived Event
            private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                SerialPort sp = (SerialPort)sender;
                while (sp.BytesToRead > 0)
                {
                    try
                    {
                        myReceivedLines.Add(sp.ReadLine());
                    }
                    catch (TimeoutException)
                    {
                        break;
                    }
                }
            }



            protected override void SolveInstance(IGH_DataAccess DA)
            {

                string selectedportname = default(string);
                DA.GetData(1, ref selectedportname);
                int selectedbaudrate = default(int);
                DA.GetData(2, ref selectedbaudrate);
                bool connecttodevice = default(bool);
                DA.GetData(3, ref connecttodevice);


                SerialPort 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


                if ((port.IsOpen) && (connecttodevice == true))
                {
                    port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                    DA.SetDataList(0, myReceivedLines);
                }

2 个答案:

答案 0 :(得分:4)

myReceivedLines = new List<string>()

答案 1 :(得分:3)

声明了

myReceivedLines,但从未赋值,因此它保持为null。您可能想要初始化它,例如:

List<string> myReceivedLines = new List<string>();

然后,您可以继续使用它。