【发布时间】:2014-06-05 12:43:18
【问题描述】:
我有一个如下代码块,我正在使用 3 个嵌套的 using 块。
我发现使用 try finally 块可以避免这种情况,但如果有两个以上 using 语句,最好的方法是什么?
private FileStream fileStream = null;
private Document document = null;
private PdfWriter pdfWriter = null;
using (fileStream = new FileStream("ABC.pdf", FileMode.Create))
{
using (document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
{
using (pdfWriter = PdfWriter.GetInstance(document, fileStream))
{
document.AddAuthor(metaInformation["author"]);
document.AddCreator(metaInformation["creator"]);
document.AddKeywords("Report Generation using I Text");
document.AddSubject("Document subject");
document.AddTitle("The document title");
}
}
}
【问题讨论】:
-
我认为这没有问题。
-
每个 using 语句都将转换为
try-finally块。所以这真的取决于你打算如何用try-finally替换你当前的结构。每个 using 块一个try/finally或多个try/finally -
你真的需要这些作为实例变量吗?在
using语句之后,它们无论如何都会被处置(因此可能无用) - 你可以将它们改为局部变量,在using语句中声明吗? -
使用
new实例化可能会失败,但会引发异常。使用Class.GetInstance()静态方法进行实例化可能会失败但返回 null。无论哪种情况,代码都应该检查并恢复。 -
Yap @ClickRick 我会重构它,谢谢
标签: c# .net using-statement