在同一语句中检查空值和流结尾 [英] check for null and end of stream in same statement

查看:30
本文介绍了在同一语句中检查空值和流结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while ((line = sr.ReadLine()) != null && !sr.EndOfStream)

这不起作用.它实际上一直在循环,我得到一个异常,因为行"为空,并且已达到 EndofStream.有什么想法吗?

This does not work. It literally keeps looping and I get an exception because "line" is null, and the EndofStream has been reached. Any idea?

推荐答案

如果你把这两个检查放在一起,即使 ReadLine() 在到达 EndOfStream 之前为空,代码也会避免循环代码>.以下是细分版本,但会贯穿整个流程.

If you put both checking together, code will escape looping even if ReadLine() is null before reaching EndOfStream. Following is a breakdown version but will go through the whole stream.

while (!sr.EndOfStream)
{
   if ((line = sr.ReadLine()) != null)
   {
      //do your work here
   }
}

这篇关于在同一语句中检查空值和流结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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