【发布时间】:2015-12-02 11:04:49
【问题描述】:
我有一个将 Action 委托作为参数的构造函数:
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
Action 没有返回值,MSDN 声明我必须为此使用 Sub (MSDN Action Delegate)。 然而,这不是真的,因为完全可以使用函数委托:
Dim executeIsCalled = False
Dim command = New DelegateCommand(Function() executeIsCalled = True)
command.Execute(Nothing)
Assert.IsTrue(executeIsCalled) ' Fail
这编译得很好,但是 executeIsCalled = True 被解释为 return 语句,导致意外结果 executeIsCalled 仍然是 false。
有趣的是,您可以执行以下操作:
Dim executeIsCalled = False
Dim command = New DelegateCommand(Function()
executeIsCalled = True
Return False
End Function)
command.Execute(Nothing)
Assert.IsTrue(executeIsCalled) ' Pass
如何防止错误地使用了 Function lambda 表达式?
【问题讨论】:
-
给出完整代码(DelegateCommand 类 + 命令实例化)。 + p 参数是干什么用的?
-
我更新了问题
-
第二个 sn-p (
Function() executeIsCalled = True) 是一个 lambda 表达式,而第三个 sn-p (Function () ... End Function) 是一个匿名函数,它们是两个不同的东西 -
谢谢 Alex,我不知道
-
不过,我怀疑是否可以只允许 Sub() 而不允许 Function()。请将此作为猜测,因为我没有证据证明:带和不带返回值的 lambda 之间的区别仅在 VB 语法(Sub()、Function())中很明显。在 C# 中,您没有这种区别
() => executeIsCalled = true);。检查 Action.Method 或 Function.Method 时,我无法观察到任何差异。我编写了一个小测试程序,并在两种情况下都使用 C# 执行 IsCalled = true。看来这只能由 .NET uber pro 来回答;)