Best practice for nested using statements?

后端 未结 5 991
情书的邮戳
情书的邮戳 2021-01-17 12:19

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

I found that using try finally blocks I can avoid this but if there a

5条回答
  •  花落未央
    2021-01-17 13:09

    A little less verbose way to avoid the indenting:

      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))
      {
           document.AddAuthor(metaInformation["author"]);
           document.AddCreator(metaInformation["creator"]);
           document.AddKeywords("Report Generation using I Text");
           document.AddSubject("Document subject - Describing the steps creating a PDF document");
           document.AddTitle("The document title - PDF creation using iTextSharp");
       }
    

    As Jon Skeet pointed out, there is no need for these variables to be instance variables, as they are disposed after the using blocks anyway.

    You can use local variables as shown in the code above instead.

提交回复
热议问题