eTreamReader何时在C#中变为null?
我看到了此链接:
代码的一部分是:
if (!File.Exists(filename))
throw new FileNotFoundException("The file does not exist.");
this.filename = filename;
string txt = String.Empty;
StreamReader sr = null;
try
{
sr = new StreamReader(filename);
txt = sr.ReadToEnd();
}
finally
{
if (sr != null) sr.Dispose();
}
eTreamReader何时null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在代码中,首先检查文件是否存在,然后创建
StreamReader
读取该文件。通过询问streamReader
何时null,您询问它何时可以构造异常。它实际上可以在几种情况下发生。如果:
streamWriter
构造期间不存在。现在我知道您在想什么:“但是它只是检查了文件是否存在”。是的,但是请考虑以下情况:streamReader
构造器,并且该文件不再存在,摘要不再存在,任何事先检查的数量都无法100%保证您将能够在下一个纳秒中读取文件。
In the code, it is first checked if the file exists, then a
StreamReader
is created which reads that file. By asking when can theStreamReader
be null, you are asking when can it's constructor throw an exception. It can actually happen in several situations.The constructor will throw an exception if:
StreamWriter
construction. Now I know what you're thinking: "But it just checked that the file exists". Yes, but consider this scenario:StreamReader
constructor is called, and the file doesn't exist anymoreIn summary, no amount of prior checking can 100% guarantee you will be able to read the file in the next nanosecond.
我认为您的问题是关于
null
在中检查
部分。streamReader sr
变量可以在最后
part中的null
,如果在new StreamReader中执行构造函数期间提出异常(文件名)
。I think your question is regarding the
null
check in thefinally
part.The
StreamReader sr
variable may benull
in thefinally
part, if an exception is raised during the execution of the constructor innew StreamReader(filename)
.