我正在做一个类的重构,并考虑用一个单独的方法移动100行.喜欢这个:
@H_301_2@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:
@H_301_2@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调用中使用的后一个值.
@H_301_2@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();