Search code examples
vb.netlambdadelegatesprocedure

.net ByRef parameter delegate sub procedure without EventHandler


I want make a class for animating. My problem I got exception: "'ByRef' parameter 'value' cannot be used in a lambda expression."

I have no idea for solve my problem. A want, my class rewrite the TestValue without EventHandler.

Here is my code:

Public Class Form1
    Dim TestValue As Single = 0
    Dim TestAnim As Animating
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TestAnim = New Animating(100, TestValue, 1, AddressOf Me.Invalidate)
    End Sub
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TestAnim.start()
    End Sub
    Private Sub Form1_Invalidated(sender As Object, e As InvalidateEventArgs) Handles Me.Invalidated
        Debug.WriteLine(TestValue)
    End Sub
End Class
Public Class Animating
    Dim _to, _value, _stepping As Single

    Public Delegate Sub Proc()
    Dim procedure As Proc

    Public Delegate Sub Resulting(ByRef V2 As Single)
    Dim procedures As Resulting

    Sub New(ByVal Vto As Single, ByRef value As Single, ByVal stepping As Single, ByRef obj As Proc)
        _to = Vto
        _value = value
        _stepping = stepping
        procedure = obj
        procedures = New Resulting(Sub()
                                       calc(value)
                                   End Sub)
    End Sub
    Sub start()
        Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(Sub()
                                                                              calc(_value)
                                                                          End Sub))
    End Sub
    Sub calc(ByRef value As Single)
        Threading.Thread.Sleep(50)
        value += _stepping
        procedures(value)
        procedure.Invoke
        If value >= _to Then Exit Sub
        calc(value)
    End Sub

End Class

Thank you for help. I use VB 2015 with .NET 2.0.


Solution

  • For the Lambda expression error, try this link. It may help you

    EDIT The error lies on the fact that you use a ByRef variable directly as a reference to the function calc()

    Try to assign it in another variable first before assigning it to the function, like

    Dim temp as Single = value
    procedures = New Resulting(Sub()
                                   calc(temp)
                               End Sub)
    

    If you clarify the question, that would be great