加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:56:56 所属栏目:百科 来源:网络整理
导读:我正在做一个类的重构,并考虑用一个单独的方法移动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)
我正在做一个类的重构,并考虑用一个单独的方法移动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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读