簡體   English   中英

IDisposable對象作為ref param to方法

[英]IDisposable objects as ref param to method

我正在進行類的重構,並考慮在一個單獨的方法中移動100行。 像這樣:

using iTextSharp.text;
using iTextSharp.text.pdf;

 class Program
{
    private static void Main(string[] args)
    {
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
        using (var mem = new MemoryStream())
        {
            using (PdfWriter wri = PdfWriter.GetInstance(doc, mem))
            {
                doc.Open();
                AddContent(ref doc, ref wri);
                doc.Close();
                File.WriteAllBytes(@"C:\testpdf.pdf", mem.ToArray());
            }
        }
    }

    public static void AddContent(ref Document doc, ref PdfWriter writer)
    {
        var header = new Paragraph("My Document") { Alignment = Element.ALIGN_CENTER };
        var paragraph = new Paragraph("Testing the iText pdf.");
        var phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here.");
        var chunk = new Chunk("This is a chunk.");
        doc.Add(header);
        doc.Add(paragraph);
        doc.Add(phrase);
        doc.Add(chunk);

    }
}

在Compiler的調用方法拋出異常: Readonly局部變量不能用作 doc和mem 的賦值目標

編輯:這里只有我在另一種方法中添加pdf文檔中的內容。 所以我需要傳遞相同的doc對象,對吧? 那么為什么我不能使用ref或out param

技術上using在這里違背了ref param的目的。

試圖在MSDN上查看:

A ReadOnly property has been found in a context that assigns a value to it. 
Only writable variables, properties, and array elements can have values assigned
to them during execution.

如何在調用Method時讀取對象? 在范圍內,對象是活着的,你可以隨心所欲。

這是因為您使用using關鍵字聲明docmem 引用MSDN

在using塊中,該對象是只讀的,不能修改或重新分配。

因此,您會收到有關只讀變量的錯誤。


如果您仍希望通過引用傳遞參數,則可以使用try ... finally塊而不是using 正如Jon Skeet所指出的,這段代碼類似於擴展using方式,但是使用using語句,它始終是處理的原始對象。 在下面的代碼中,如果AddContent更改doc的值,它將是Dispose調用中使用的更晚值。

var doc = new Document(PageSize.A4, 5f, 5f, 5f, 5f);
try
{
     var mem = new MemoryStream();
     try
     {
         PdfWriter wri = PdfWriter.GetInstance(doc, output);
         doc.Open();
         AddContent(ref doc,ref wri );
         doc.Close();
     }
     finally
     {
         if (mem != null)
             ((IDisposable)mem).Dispose();
     }
 }
 finally
 {
     if (doc != null)
         ((IDisposable)doc).Dispose();
 }
 return output.ToArray();

mem變量是readonly,因為using關鍵字。 當你重寫它對變量的引用時,編譯器應該如何知道在離開using-scope時他必須處置什么。

但是為什么你還要使用ref關鍵字呢? 在我看來,你不需要參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM