为什么 param 出现在这个 lambda 表达式中?
Josh Smith 关于 MVVM 的 MSDN 杂志文章包含一个 lambda 表达式 I不完全明白。这段代码中 param 的用途是什么?
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
翻译成我的首选语言 VB 是:
Dim saveAction as New Action(Of Object)(AddressOf Me.Save)
_saveCommand = New RelayCommand(saveAction, Function(param) Me.CanSave)
如果在 CanSave 或 Save 中使用param,我预计只会看到它。我对 lambda 表达式有点陌生。据我所知,看到一个既没有声明也没有在任何地方使用的变量对我来说很奇怪。任何解释将不胜感激。
为了将其放在上下文中,RelayCommand (C#) 的构造函数为:
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
在 VB 中:
Public Sub New(ByVal execute As Action(Of Object), _
ByVal canExecute As Predicate(Of Object))
The MSDN magazine article by Josh Smith on MVVM contains a lambda expression I don't completely understand. What is the purpose of param in this code?
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
Translated to my preferred language VB it's:
Dim saveAction as New Action(Of Object)(AddressOf Me.Save)
_saveCommand = New RelayCommand(saveAction, Function(param) Me.CanSave)
I would have expected to only see param if it is used within CanSave or Save. I am somewhat new to lambda expressions. It's odd for me to see a variable that is neither declared nor used anywhere as far as I can tell. Any explanation would be appreciated.
To put this in context the constructor for RelayCommand (C#) is:
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
and in VB:
Public Sub New(ByVal execute As Action(Of Object), _
ByVal canExecute As Predicate(Of Object))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
lambda 表达式正在声明它 - 它出现的地方基本上是一个声明。如果没有,它将与
Action(Of Object)
不兼容。这就是它存在的原因 - 即使您实际上并不需要该值。使用匿名方法,如果不需要任何参数值,则可以完全省略参数列表:
...但不能使用 lambda 表达式做到这一点。您必须指定参数列表 - 要么只是作为单个参数的参数名称,要么是括号中的完整列表。您提供的代码相当于:
The lambda expression is declaring it - the place where it appears is basically a declaration. If it didn't, it wouldn't be compatible with
Action(Of Object)
. That's why it's there - even though you don't actually need the value.With anonymous methods, if you don't need any parameter values you can omit the parameter list entirely:
... but you can't do that with lambda expressions. You have to specify the parameter list - either just as a parameter name for a single parameter, or a full list in brackets. The code you've presented is equivalent to: