开发者

What am I missing about numeric comparisons in this simple delegate example?

I am looking specifically at the ShowInOrder method which has been passed the delegate function CompareNumbers. I am trying to figure out exactly what is going on here:

If compare(_num1, _num2) Then ...

Here is the full sample. Any help would be appreciated.

Module Module1

Sub Main()
    ' Create an instance of InOrderClass and assign values to the properties.
    ' InOrderClass method ShowInOrder displays the numbers in ascending 
    ' or descending order, depending on the comparison method you specify.
    Dim inOrder As New InOrderClass
    inOrder.Num1 = 5
    inOrder.Num2 = 4

    ' Use AddressOf to send a reference to the comparison function you want
    ' to use.
    inOrder.ShowInOrder(AddressOf GreaterThan)
    inOrder.ShowInOrder(AddressOf LessThan)

    ' Use lambda expressions to do the same thing.
    inOrder.ShowInOrder(Function(m, n) m > n)
    inOrder.ShowInOrder(Function(m, n) m < n)
End Sub

Function GreaterThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
    Return num1 > num2
End Function

Function LessThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
    Return num1 < num2
End Function

Class InOrderClass
    ' Define the delegate function for the comparisons.
    Delegate Function CompareNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
    ' Display properties in ascending or descending order.
    Sub ShowInOrder(ByVa开发者_运维知识库l compare As CompareNumbers)
        If compare(_num1, _num2) Then
            Console.WriteLine(_num1 & "  " & _num2)
        Else
            Console.WriteLine(_num2 & "  " & _num1)
        End If
    End Sub

    Private _num1 As Integer
    Property Num1() As Integer
        Get
            Return _num1
        End Get
        Set(ByVal value As Integer)
            _num1 = value
        End Set
    End Property

    Private _num2 As Integer
    Property Num2() As Integer
        Get
            Return _num2
        End Get
        Set(ByVal value As Integer)
            _num2 = value
        End Set
    End Property
End Class

End Module


compare is a pointer to a function, in your sample 2 obtained by AddressOf and 2 by creating a lambda function. Calling compare means transfer execution to the code pointed to. The class executes a routine, but has no idea what it's like. Only certainty is that the parameters and the returnvalue match the type of your variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜