我有一些像这样的代码。
using (StreamWriter sw = new StreamWriter(@"c:\SomeFile.txt"))
{
using (IDataReader reader = SomeMethodThatReturnsADataReader())
{
while (reader.Read())
{
// using sw and reader here
}
}
sw.Close();
}
警告后的代码分析报告。
CA2202多次弃置物品对象' sw'可 方法不止一次处理。为了避免产生 System.ObjectDisposedException你不应该调用Dispose 一次在一个物体上。
我在这里做错了什么?
答案 0 :(得分:1)
正如我们从StreamWriter.Dispose()
看到的那样,Close
方法在其中被调用。
protected override void Dispose(bool disposing)
{
try
{
if (this.stream != null && (disposing || (this.LeaveOpen && this.stream is __ConsoleStream)))
{
this.CheckAsyncTaskInProgress();
this.Flush(true, true);
if (this.mdaHelper != null)
{
GC.SuppressFinalize(this.mdaHelper);
}
}
}
finally
{
if (!this.LeaveOpen && this.stream != null)
{
try
{
if (disposing)
{
this.stream.Close();
}
}
finally
{
this.stream = null;
this.byteBuffer = null;
this.charBuffer = null;
this.encoding = null;
this.encoder = null;
this.charLen = 0;
base.Dispose(disposing);
}
}
}
}