我正在进行类的重构,并考虑在一个单独的方法中移动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时读取对象?在范围内,对象是活着的,你可以随心所欲.
的mem
变量是只读的,因为的using
关键字.当你重写它对变量的引用时,编译器应该如何知道在离开using-scope时他必须处置什么.
但是为什么你还要使用ref
关键字呢?在我看来,你不需要参考.
这是因为您声明doc
并mem
使用了using
关键字.引用MSDN:
在using块中,该对象是只读的,不能修改或重新分配.
因此,您会收到有关只读变量的错误.
如果您仍希望通过引用传递参数,则可以使用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();