【问题标题】:Exceptions: System.NullReferenceException [duplicate]例外:System.NullReferenceException [重复]
【发布时间】:2012-02-12 23:37:43
【问题描述】:

可能重复:
NullReferenceException on instanciated object?
What is a NullReferenceException in .NET?

我在 C# 中构建了一个 TCP 客户端,当客户端无法连接时,我得到以下信息。 我不断收到以下代码的 NullReference 异常,我不知道如何捕获或停止它。任何帮助将不胜感激。

它发生在“int a = sReponseData.Length”

    {



        string sMesg = "LogOn Ext:" + txtdevice.Text;
        SendMessage(sMesg);


        int a = sResponseData.Length;


        //Geting the Script out of the message.

        if (a > 10)
        {
            string stemp = sResponseData;
            string[] sSplit = stemp.Split(new Char[] { ';'});
            foreach (string s in sSplit)
            {

                if ((s.Trim() != "Tag") & (s.Trim() != "StopStart"))
                    sScript = s;
            }
        }
     }

}

这里是短信

    {
        InitializeComponent();
        try
        {
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer 
            // connected to the same address as specified by the server, port
            // combination.
            //Int32 port = 13000;
            TcpClient client = new TcpClient("127.0.0.1", 32111);

            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes(sMsg);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);

            //MessageBox.Show("Sent: {0}" + sMsg);

            // Receive the TcpServer.response.


            // String to store the response ASCII representation.
            sResponseData = String.Empty;

            if (stream.CanRead)
            {
                byte[] myReadBuffer = new byte[1024];
                StringBuilder myCompleteMessage = new StringBuilder();
                int numberOfBytesRead = 0;

                // Incoming message may be larger than the buffer size.
                do
                {
                    numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);

                    myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

                }
                while (stream.DataAvailable);

                // Print out the received message to the console.
                sResponseData = myCompleteMessage.ToString();
                //MessageBox.Show(sResponseData);
            }
            else
            {
                sResponseData = ("3");
                MessageBox.Show("TagIt Server is unavalible at this moment.");
            }

            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            WriteLog("ArgumentNullException: {0}" + e);
            MessageBox.Show("TagIt Server is unavalible at this moment.");
        }
        catch (SocketException e)
        {
            WriteLog("SocketException: {0}" + e);
            MessageBox.Show("TagIt Server is unavalible at this moment.");
        }

    }

【问题讨论】:

  • 在代码的哪一行你得到了异常?阅读整个异常消息。
  • 该行中唯一可以为空的是sResponseData。所以我猜第二个函数永远不会被调用,但如果没有更多信息就不可能知道。启动调试器并验证 sResponseData 实际上是否为 null 您收到错误的位置,您的第二个函数以查看它是否被调用,如果没有,则无论哪个函数调用它以查看它被跳过的原因,等等。跨度>

标签: c# nullreferenceexception


【解决方案1】:

您可以检查响应数据是否有价值:

类似:

 int a;
 try
 {
 if(sResponseData==null || sResponseData=="" )
  {
  MessageBox.Show("ResponseData is NULL or Empty"); //Shows Error 
  }
  else
  {
    //SresponseData has value
    string sMesg = "LogOn Ext:" + txtdevice.Text;
    SendMessage(sMesg);


     a= Convert.ToInt32(sResponseData).Length;

    //Geting the Script out of the message.

    if (a > 10)
    {
        string stemp = sResponseData;
        string[] sSplit = stemp.Split(new Char[] { ';'});
        foreach (string s in sSplit)
        {

            if ((s.Trim() != "Tag") & (s.Trim() != "StopStart"))
                sScript = s;
        }
    }
  }
 }
 catch (Execption ex)
 {
 MessageBox.Show(ex.Message); //Shows Error 
 }

【讨论】:

    【解决方案2】:

    在检查 sResponseData 的长度之前,请确保检查 sResponseData 是否为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2017-07-15
      相关资源
      最近更新 更多