委托System.Action不带1个参数 [英] Delegate System.Action does not take 1 arguments

查看:152
本文介绍了委托System.Action不带1个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动作:

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;
}

其他班级的代码:

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?

代理'System.Action'不接受1个参数

推荐答案

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

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

要解决此问题,请将您的RelayAction类替换为以下内容

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
}

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

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.

一些MSDN链接:

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

这篇关于委托System.Action不带1个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆