我可以使用 AddHandler 将委托子分配给 AddHandler 吗?

Can I assign delegate sub to AddHandler using AddressOf?

编辑:我原来的问题太混乱了。

Public Class PrintResults

    Public Sub ResultsToPS(ByVal lis As List(Of FileData), ByVal PSPathName As String) 
        Me.List = lis

        'setup report writer
        Dim rep As New Helper.Report

        'create report to PS
        rep.ToPS(PSPathName)

    End Sub


Public Class Report
    Public Sub New()
        PrintDoc = New Printing.PrintDocument
    End Sub

    Public WithEvents PrintDoc As Printing.PrintDocument

    Public PrintDocPrintPage As PrintDoc_PrintPage
    Public Delegate Sub PrintDoc_PrintPage(ByVal sender As Object, _
                        ByVal e As Printing.PrintPageEventArgs) 'Handles PrintDoc.PrintPage 

    Public Function ToPS(ByVal PSPathName As String) As String

        'fails
        AddHandler Me.PrintDoc.PrintPage, AddressOf Me.PrintDocPrintPage

        Me.PrintDoc.Print()

    End Function

AddHandler 出现编译器错误:AddressOf 操作数必须是方法的名称。有没有办法将处理程序分配给委托子?

也许您正在寻找创建事件并为其附加功能。

Sub Main()

    Dim c As New TestClass

    AddHandler c.OnComplete, AddressOf Test

    c.Execute() ' Will print Done

    Console.ReadLine()

End Sub

Sub Test()
    Console.WriteLine("Done")
End Sub

Class TestClass

    Public Event OnComplete()

    Public Sub Execute()
        RaiseEvent OnComplete()
    End Sub

End Class

通过一些研究,我发现无法将委托子与 AddressOf 一起使用。所以我们需要一种不同的方法。现在我明白了,我所要做的就是在 New sub 中实例化 PrintDoc。现在我有一个供 AddHandler 使用的 PrintDoc 对象。

Public Class Report
    Public Sub New()
        PrintDoc = New Printing.PrintDocument
    End Sub

我们使用没有委托的常规 AddHandler:

Public Class PrintResults

    Public Sub ResultsToPS(ByVal lis As List(Of FileData), ByVal PSPathName As String) 
        Me.List = lis

        'setup report writer
        Dim rep As New Helper.Report

        'PrintDoc is automatically instatiated so no object error
        AddHandler rep.PrintDoc.PrintPage, AddressOf Me.PrintDoc_PrintPage      

        'create report to PS
        rep.ToPS(PSPathName)

    End Sub

Delegates and the AddressOf Operator

AddHandler Statement