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

时间:2016-08-26 15:28:06

标签: vb.net delegates printdocument

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

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操作数必须是方法的名称。有没有办法将处理程序分配给委托子?

2 个答案:

答案 0 :(得分:0)

可能正在寻找创建事件并将功能附加到它上面。

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

答案 1 :(得分:0)

通过一些研究,我发现使用AddressOf的委托子是不可能的。所以我们需要一种不同的方法。我现在看到我要做的就是在New子实例化PrintDoc。现在我有一个PrintDoc对象供AddHandler使用。

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