C# 委托 System.Action 不接受 1 个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14029596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:28:03  来源:igfitidea点击:

Delegate System.Action does not take 1 arguments

c#lambdaaction

提问by idish

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

委托“System.Action”不接受 1 个参数

采纳答案by J0HN

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

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

To fix this, replace your RelayActionclass with something lie the following

要解决此问题,请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
}

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

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

Some MSDN links:

一些 MSDN 链接:

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

回答by Trinitron

You can define your command 'RemoveReferenceExcecute' without any parameters

您可以在没有任何参数的情况下定义您的命令“RemoveReferenceExcecute”

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;

在第二种情况下,不要忘记从您的视图中传递 CommandParameter;