开发者

Why is param in this lambda expression?

开发者 https://www.devze.com 2023-01-08 08:17 出处:网络
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?

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 w开发者_如何学Goithin 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))


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:

_saveCommand = new RelayCommand(delegate { this.Save(); },
     delegate { return this.CanSave; });

... 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:

_saveCommand = new RelayCommand((Object param) => this.Save(),
     (Object param) => this.CanSave);
0

精彩评论

暂无评论...
验证码 换一张
取 消