Tag: ca2202

多次处置对象

我有以下代码,它使用流来打开和修改Open XML文档,然后保存该流的新二进制表示: MemoryStream stream = null; try { stream = new MemoryStream(); stream.Write(this.GetBinaryRepresentation(), 0, this.GetBinaryRepresentation().Length); using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true)) { OfficeDocument.ModifyDocument(document); this.SetBinaryRepresentation(stream.ToArray()); stream = null; } } finally { if (stream != null) { stream.Dispose(); } } 我最初使用了两个使用块(一个用于MemoryStream,第二个用于WordprocessingDocument),但收到警告CA2202:“对象’流’可以在方法中多次丢弃…”根据MSDN文章 ,我修改了上面的代码(将外部使用转换为试用),但我仍然收到此警告。 我不确定如何构造此方法以确保在流上只调用一次Dispose。 我不想简单地抑制此警告,因为MSDN文章声明您不应该依赖Dispose多次安全地调用。