c# – IDisposable对象作为ref参考方法

我正在做一个类的重构,并考虑用一个单独的方法移动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,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);

    }
}

在编译器的调用方法中抛出异常:只读本地变量不能用作doc和mem的赋值对象.

编辑:这里只有我以其他方式在pdf文档中添加内容.所以我需要传递相同的doc对象,对吧?所以为什么我不能使用ref或out参数.

在技​​术上使用ref在这里ref ref的目的.

试图看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.

调用方法时,对象如何变为只读?在范围内的对象是活着的,你可以做任何你想要的.

解决方法

这是因为您使用using关键字声明doc和mem.引用 MSDN

Within the using block,the object is read-only and cannot be modified or reassigned.

因此,您会收到有关只读变量的错误.

如果您仍然希望通过引用传递参数,可以使用try … finally块而不是使用.正如Jon Skeet所指出的那样,这段代码与使用是如何扩展但是使用语句相似的,它总是被处理的原始对象.在下面的代码中,如果AddContent更改了doc的值,那么它将是在dispose调用中使用的后一个值.

var doc = new Document(PageSize.A4,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();

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...