嵌套using语句的最佳实践? [英] Best practice for nested using statements?

查看:185
本文介绍了嵌套using语句的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的代码块,并且我正在使用3个嵌套的 using 块。

I have a code block as follows and I'm using 3 nested using blocks.

我发现最终使用 try 块可以避免这种情况,但是如果有两个以上using语句,那最好的方法是什么?

I found that using try finally blocks I can avoid this but if there are more than two using statements, what is the best approach?

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");
        }
    }
}


推荐答案

您可以通过以下方式删除缩进和大括号:

You can remove the indention and curly brackets this way:

using (var fileStream = new FileStream("ABC.pdf", FileMode.Create))
using (var document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
using (var pdfWriter = PdfWriter.GetInstance(document, fileStream))
{
   // code
}

这篇关于嵌套using语句的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆