委托System.Action不带1个参数

idi*_*ish 3 c# lambda 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;
}
Run Code Online (Sandbox Code Playgroud)

其他课程代码:

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

private void RemoveReferenceExcecute(object param)
{
    ReferenceViewModel referenceViewModel = (ReferenceViewModel) param;
    ReferenceCollection.Remove(referenceViewModel);
}
Run Code Online (Sandbox Code Playgroud)

为什么我会得到以下异常,我该如何解决?

委托'System.Action'不带1个参数

J0H*_*0HN 8

System.Action是无参数函数的委托.使用System.Action<T>.

要解决此问题,请RelayAction使用以下内容替换您的课程

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

注意RelayAction类应该是通用的.另一种方法是直接指定_execute将接收的参数类型,但这样您将被限制使用您的RelayAction类.因此,在灵活性和稳健性之间存在一些权衡.

一些MSDN链接:

  1. System.Action
  2. System.Action<T>