Stream
、StreamReader
、StreamWriter
等类实现了IDisposable
接口(interface)。这意味着,我们可以在这些类的对象上调用 Dispose()
方法。他们还定义了一个名为 Close()
的 public
方法。现在让我感到困惑的是,一旦我处理完对象后我应该调用什么?如果我同时调用两者怎么办?
我目前的代码是这样的:
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(filename))
{
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
writer.Close();
}
reader.Close();
}
}
如您所见,我编写了 using()
结构,它会自动调用每个对象的 Dispose()
方法。但我也调用了 Close()
方法。对吗?
请建议我使用流对象时的最佳实践。 :-)
MSDN 示例不使用 using()
构造,而是调用 Close()
方法:
好吃吗?
最佳答案
快速跳转到 Reflector.NET 显示 StreamWriter
上的 Close()
方法是:
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
StreamReader
是:
public override void Close()
{
this.Dispose(true);
}
StreamReader
中的 Dispose(bool disposing)
覆盖是:
protected override void Dispose(bool disposing)
{
try
{
if ((this.Closable && disposing) && (this.stream != null))
{
this.stream.Close();
}
}
finally
{
if (this.Closable && (this.stream != null))
{
this.stream = null;
/* deleted for brevity */
base.Dispose(disposing);
}
}
}
StreamWriter
方法类似。
因此,阅读代码很明显,您可以根据需要以任何顺序对流调用 Close()
和 Dispose()
。它不会以任何方式改变行为。
因此归结为使用 Dispose()
、Close()
和/或 using ( ... ) 是否更具可读性{ ... }
。
我个人的偏好是尽可能使用 using ( ... ) { ... }
,因为它可以帮助您“不用剪刀跑”。
但是,虽然这有助于正确性,但确实会降低可读性。在 C# 中,我们已经有过多的右花括号,那么我们如何知道哪个真正执行流上的关闭?
所以我认为最好这样做:
using (var stream = ...)
{
/* code */
stream.Close();
}
它不会影响代码的行为,但确实有助于提高可读性。
关于c# - 我应该为流对象调用 Close() 还是 Dispose()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7524903/