0

运行下面的代码时,我得到以下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);
                }
4

2 回答 2

4
myReceivedLines = new List<string>()
于 2012-10-14T19:35:25.550 回答
3

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

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

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

于 2012-10-14T19:36:16.320 回答