我们为什么要在之前streamreader使用c#
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*ana 10
在处理一次性物体时,在C#中使用块非常方便.一次性对象是那些可以在调用dispose时显式释放它们使用的资源的对象.我们知道.Net垃圾收集是非确定性的,因此您无法预测对象何时会被垃圾收集.
阅读这篇文章了解更多详情:了解C#中的'using'块
using在您使用实现的对象时IDisposable(StreamReader不管这样做),使用语法是一种很好的做法,因为它确保Dispose始终调用该方法并正确处理该对象.
例如,在这种情况下,将在文件" TestFile.txt " 上获得各种句柄/锁,这可以防止其他人写入或甚至读取该文件,直到流阅读器被丢弃或者过程结束.其他对象(例如数据库对象)可能会耗尽数据库连接或网络资源,因此您应该在使用完对象后立即处置对象 - 在执行此操作时,using语句只是一个简单而安全的模式.
在幕后发生的事情与此类似(参考):
StreamReader sr = new StreamReader("TestFile.txt");
try
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
finally
{
if (sr != null)
{
((IDisposable)sr).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,使用声明比尝试IDisposable手动处理更清晰(并且更不容易出错).