IDisposable对象作为ref param to方法

 dsjdsjdsjjk_896 发布于 2023-02-09 14:51

我正在进行类的重构,并考虑在一个单独的方法中移动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或者不使用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时读取对象?在范围内,对象是活着的,你可以随心所欲.

2 个回答
  • mem变量是只读的,因为的using关键字.当你重写它对变量的引用时,编译器应该如何知道在离开using-scope时他必须处置什么.

    但是为什么你还要使用ref关键字呢?在我看来,你不需要参考.

    2023-02-09 14:54 回答
  • 这是因为您声明docmem使用了using关键字.引用MSDN:

    在using块中,该对象是只读的,不能修改或重新分配.

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


    如果您仍希望通过引用传递参数,则可以使用try ... finallyblock而不是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();
    

    2023-02-09 14:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有