使用方法更改对象引用值

Using a method to change object reference values

这是一个 PDFSharp 问题,但我认为它更准确地属于对象引用在 vb.net 中的工作方式范围。

所以我的代码看起来像这样:

Dim page as PdfPage = pdf1.AddPage()
Dim graphics as XGraphics = XGraphics.FromPdfPage(pdfPage)

所以这很自然地创建了我需要的图形 XGraphics 和 PdfPage 对象。

现在,当我需要向正在创建的 PDF 文档添加页面时,我调用代码:

page = pdf1.AddPage()
graphics = XGraphics.FromPdfPage(pdfPage)

当然,还有一些其他的事情我也在做,比如添加XTextFormatters,定义我的起始X,Y坐标等等。但是足以说明我是一个懒惰的人,我尝试编写一个方法允许我传递我想要的所有变量,并自动为我更新所有这些。简而言之,类似于:

Private Sub ConductPrinting()
    Dim pdf1 as New Pdf
    Dim page as PdfPage = pdf1.AddPage()
    Dim graphics as XGraphics = XGraphics.FromPdfPage(pdfPage)

    'Printing code here
    'Printing code here
    'Printing code here

    'Start new page code
    pdfPage = pdf1.AddPage()
    graphics = XGraphics.FromPdfPage(pdfPage)
End Sub

我想写一个StartNewPage()方法,像这样:

Private Sub StartNewPage(pdf1 As Pdf, page As PdfPage, graphics As XGraphics) As Integer
    pdfPage = pdf1.AddPage()
    graphics = XGraphics.FromPdfPage(pdfPage)
End Sub

以便代码块看起来像这样:

Private Sub ConductPrinting()
    Dim pdf1 as New Pdf
    Dim page as PdfPage = pdf1.AddPage()
    Dim graphics as XGraphics = XGraphics.FromPdfPage(pdfPage)

    'Printing code here
    'Printing code here
    'Printing code here

    'Start new page code
    StartNewPage(pdf1, page, graphics)
End Sub

你会怎么做?因为这行不通;页面和图形仍然引用旧页面和图形。

您需要通过引用而不是值来传递要更改的对象,所以...

Private Sub StartNewPage(pdf1 As Pdf, ByRef page As PdfPage, ByRef graphics As XGraphics)

来自Passing Arguments by Value and by Reference (Visual Basic)

When to Pass an Argument by Reference
If the procedure has a genuine need to change the underlying element in the calling code, declare the corresponding parameter ByRef.