简体   繁体   English

未设置对象引用C#

[英]Object reference not set c#

I've made an application that communicates via a second application TCP and I get an error: 我制作了一个通过第二个应用程序TCP进行通信的应用程序,但出现错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.NullReferenceException:'对象引用未设置为对象的实例。 --> s was null at the while loop. -> s在while循环中为null。

This error only occurs when I forcefully close the second application (By pressing the X at the top of the app or killing it via task manager) that is still connected with the first one. 仅当我强制关闭仍与第一个应用程序连接的第二个应用程序(通过按应用程序顶部的X或通过任务管理器将其杀死)时,才会发生此错误。

My first application that receives commands and prints them out: 我的第一个接收命令并打印出来的应用程序:

try
{
    StreamReader reader = new StreamReader(client.GetStream());
    StreamWriter writer = new StreamWriter(client.GetStream());
    string s = String.Empty;
    while (!(s = reader.ReadLine()).Equals("PING"))
        Console.WriteLine(s);
    reader.Close();
    writer.Close();
    client.Close();
}
catch (IOException)
{
    Console.WriteLine("woops an error!");
}

My second application that sends the commands: 我的第二个发送命令的应用程序:

try
{
    TcpClient client = new TcpClient("192.168.0.107", 8080);
    StreamReader reader = new StreamReader(client.GetStream());
    StreamWriter writer = new StreamWriter(client.GetStream());
    writer.WriteLine("PING");
    writer.Flush();
    reader.Close();
    writer.Close();
    client.Close();
}catch(Exception ex)
    Console.WriteLine(ex.Message);

I tried checking if s==null(like below) and it still throws an exception. 我尝试检查s == null(如下所示)是否仍然抛出异常。

while (!(s = reader.ReadLine()).Equals("PING") || (s==null))

If reader.ReadLine() returns null, null will be assigned to s and then you'll immediately call .Equals on the null (any assignment automatically returns the value that was assigned).. the s == null does nothing to prevent this and indeed it cannot; 如果reader.ReadLine()返回null,则将为s分配null,然后您将立即调用。等于null(任何赋值都会自动返回已分配的值)。s == null不能防止这种情况确实不能; swapping it to the left wouldn't help either because the brackets take precedence - you need to check it for null before you call .Equals on it 将其交换到左侧也无济于事,因为方括号优先-您需要在调用前检查它是否为null。

You'd be better off using a for loop and not trying to do so much in one statement 您最好使用for循环,而不要在一个语句中尝试做太多事情

for(s = reader.ReadLine(); s!=null && s.Equals("PING"); s = reader.ReadLine())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM