我有以下代码,它使用流打开和修改 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我最初使用了两个 using 块(一个用于 MemoryStream,第二个用于 WordprocessingDocument),但收到警告 CA2202:“对象‘流’可以在方法中多次处理......”根据MSDN 文章,我修改了代码到上面(将外部使用转换为尝试),但我仍然收到此警告。
我不确定如何构造此方法以确保在流上只调用一次 Dispose。我不想简单地取消此警告,因为 MSDN 文章指出您不应该依赖 Dispose 可以多次安全调用。
如果一个对象的 Dispose 方法被多次调用,则该对象必须忽略第一次之后的所有调用。如果多次调用对象的 Dispose 方法,则该对象不得引发异常。
话虽如此, using 语句绝对是这里的方法。您收到该方法的唯一原因是,如果您显式处理对象,这不是必需的,因为 using 语句应该始终只处理一次对象。
| 归档时间: |
|
| 查看次数: |
4159 次 |
| 最近记录: |