我有一個構造函數的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')是一個匿名函數,它是兩個不同的東西 –