我有一个构造函数的Action委托作为参数:Action委托接受函数lambda表达式
Public Class DelegateCommand
Public Sub New(execute As Action(Of T))
Me.New(execute, Nothing)
End Sub
End Command
' This works as expected
Dim executeIsCalled = False
Dim command = New DelegateCommand(Sub() executeIsCalled = True)
command.Execute(Nothing)
Assert.IsTrue(executeIsCalled) ' Pass
行动没有返回值和MSDN指出,我必须使用一个子为此目的(MSDN Action Delegate)。
Dim executeIsCalled = False
Dim command = New DelegateCommand(Function() executeIsCalled = True)
command.Execute(Nothing)
Assert.IsTrue(executeIsCalled) ' Fail
编译没有问题,但是executeIsCalled = True
被解释为return语句,导致意外结果executeIsCalled
仍然是假: 然而,因为它是完全有可能用一个函数委托,这是不正确的。 有趣的是,你可以做到以下几点:
Dim executeIsCalled = False
Dim command = New DelegateCommand(Function()
executeIsCalled = True
Return False
End Function)
command.Execute(Nothing)
Assert.IsTrue(executeIsCalled) ' Pass
我怎样才能稳定,防止因误操作而一个功能lambda表达式中使用?
给出完整的代码(DelegateCommand类+命令实例化)。 +什么是p参数用于? –
我更新了问题 –
第二个片段('Function()executeIsCalled = True')是一个lambda表达式,而第三个片段('Function()... End Function')是一个匿名函数,它是两个不同的东西 –