c# - IDisposable 对象作为方法的 ref 参数

标签 c#

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

    }
}

在调用编译器的方法时抛出异常:Readonly local variable cannot be used as an assignment target for doc and mem.

编辑:这里我只是用另一种方法在pdf文档中添加内容。所以我需要传递相同的文档对象,对吗?那么为什么我不能使用 refparam

技术上 using 违背了 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 关键字声明了 docmem。引用 MSDN :

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

因此你得到关于只读变量的错误。


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

关于c# - IDisposable 对象作为方法的 ref 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20655757/

相关文章:

c# - 动态调度和绑定(bind)

c# - 创建自定义事件处理程序时如何在 sitecore 中获取项目的字段名称

C# 命名空间 : Calling Methods and Classes

c# - 帮助为我的类创建一个基本接口(interface)

c# - 找不到如何使用 HttpContent

c# - 在 Windows 窗体中进行验证的最佳方法是什么

c# - 您如何强制控制台应用程序项目在构建中包含一个文件夹?

c# - 更改界面会破坏现有客户端吗

c# - 在 C# 中引发异常时调用服务的析构函数

c# - LINQ 按总和值分组