Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate System.Action does not take 1 arguments

Tags:

c#

lambda

action

The action :

readonly Action _execute;

public RelayCommand(Action execute)
             : this(execute, null)
{
}

public RelayCommand(Action execute, Func<Boolean> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");
    _execute = execute;
    _canExecute = canExecute;
}

Other class's code:

public void CreateCommand()
{
    RelayCommand command = new RelayCommand((param)=> RemoveReferenceExcecute(param));}
}

private void RemoveReferenceExcecute(object param)
{
    ReferenceViewModel referenceViewModel = (ReferenceViewModel) param;
    ReferenceCollection.Remove(referenceViewModel);
}

Why do I get the following exception, how can I fix it?

Delegate 'System.Action' does not take 1 arguments

like image 537
idish Avatar asked Dec 25 '12 09:12

idish


2 Answers

System.Action is a delegate for parameterless function. Use System.Action<T>.

To fix this, replace your RelayAction class with something like the following

class RelayAction<T> {
    readonly Action<T> _execute;
    public RelayCommand(Action<T> execute, Func<Boolean> canExecute){
        //your code here
    }
    // the rest of the class definition
}

Note RelayAction class should become generic. Another way is to directly specify the type of parameter _execute will receive, but this way you'll be restricted in usage of your RelayAction class. So, there are some tradeoff between flexibility and robustness.

Some MSDN links:

  1. System.Action
  2. System.Action<T>
like image 168
J0HN Avatar answered Nov 14 '22 23:11

J0HN


You can define your command 'RemoveReferenceExcecute' without any parameters

RelayCommand command = new RelayCommand(RemoveReferenceExcecute);}

or you can pass some parameters / objects into it:

RelayCommand<object> command = new RelayCommand<object>((param)=> RemoveReferenceExcecute(param));}

In the second case do not forget to pass CommandParameter from your view;

like image 43
Trinitron Avatar answered Nov 14 '22 23:11

Trinitron