如何解决NullReferenceException异常? [英] How to solve exception of NullReferenceException?

查看:165
本文介绍了如何解决NullReferenceException异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为多个客户端服务器编写代码,并且它正在工作.但是我想在表单文本框上显示数据对话,为此我在form1.cs中有以下方法,如果从同一个类进行调用,则会运行该方法,但是从另一个类handleClient.cs进行调用时,此方法将不起作用,并且给出对象引用未设置为实例:空引用异常"错误,但是当我在其中放置断点时,它在循环中显示数据,但在循环后立即中断,并且不显示数据.
错误在"AppendTxtdata"方法中的粗体字处.

这是用于更好理解的代码,

form1.cs.

I am trying to write code for multiple client server and it is working . But I want to display data conversation on form textbox, for that I have following method in form1.cs which if calling from same class this runs but when calling from another class handleClient.cs this doesnt works and giving "object reference not set to an instance : null reference exception" error but when I putted breakpoint there it shows data in loop but break just after the loop and doesn''t displays data.
The error is at the bold line in "AppendTxtdata" method.

here is the code for better understanding,

form1.cs.

public void AppendTxtdata(string val)
{
try
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTxtdata), new object[] { val });
return;
}
txtdata.Text += val;
}
catch { }
}



handleClient.cs



handleClient.cs

public void GetData() // to run server //
{
Form1 f = new Form1();

try
{
NetworkStream networkStream = clientSocket.GetStream();


for (int p = 0; p >= 0; p++)
{
byte[] b = new byte[100];

int k = networkStream.Read(b, 0, b.Length);

f.AppendTxtdata("The Data from Client ( " + clNo + " ) Recieved..." + Environment.NewLine);

for (int i = 0; i < k; i++)
{
f.AppendTxtdata("" + Convert.ToChar(b[i]));
}

f.AppendTxtdata(Environment.NewLine);

var j = b.Length - 1;
while (b[j] == 0)
{
    --j;
}

    var temp = new byte[j + 1];
    Array.Copy(b, temp, j + 1);

    string res = System.Text.Encoding.ASCII.GetString(temp);

}

推荐答案

首先在调试器中运行您的应用,当发生异常时,它将在显示问题的那一行中断执行. br/> 然后,使用调试器检查该行中的所有变量,并找出其中一个包含null值的变量.然后,您可以使用堆栈跟踪和其余代码来找出为什么它为null.

我们无法为您做到这一点:我们无法在与您完全相同的条件下运行您的代码.
因此,开始寻找并准确找出哪一行,哪一个变量.当您知道这一点时,应该更清楚为什么它为null.但是直到获得该信息,才可以猜测.
Start by running your app in the debugger, and when the exception occurs, it will break execution at the line that showed the problem.
Then use the debugger to examine all the variables in the line, and find out which one contains the null value. You can then use the stack trace and the rest of your code to find out why it is null.

We can''t do that for you: we can''t run your code under the exact same conditions as you do.
So start looking and find out exactly which line, and which variable. When you know that, it should become clearer why it''s null. But until you have that info, it''s just guess work.


这篇关于如何解决NullReferenceException异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆