How to declare lambda event handlers in VB.Net?

前端 未结 4 1417
盖世英雄少女心
盖世英雄少女心 2021-02-07 02:44

I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.

What is going

4条回答
  •  我在风中等你
    2021-02-07 03:25

    Note: This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10

    The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression eventRaised = true is being interpreted as a boolean expression rather than an assignment i.e. is evaluating to false rather than setting to true.

    Further details on MSDN.

    I'm don't think the c# pattern for testing events used in the example can be done in VB.Net without introducing another function e.g.

     _
    Public Class Test
         _
        Public Sub EventTest()
            Dim eventClass As New EventClass
            Dim eventRaised As Boolean = False
            AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised))
            eventClass.RaiseIt()
            Assert.IsTrue(eventRaised)
        End Sub
    
        Private Function SetValueToTrue(ByRef value As Boolean) As Boolean
            value = True
            Return True
        End Function
    
    End Class
    
    Public Class EventClass
        Public Event AnEvent()
        Public Sub RaiseIt()
            RaiseEvent AnEvent()
        End Sub
    End Class
    

提交回复
热议问题