Action,Func和Predicate委托 - C#

Asa*_*saf 5 .net c# wpf delegates mvvm

我试图理解Action<T>, Func<T> and Predicate<T>代表之间的差异,作为我的WPF/MVVM学习的一部分.

我知道Action<T> and Func<T>两个都是零到一个+参数,只Func<T>返回一个值,而Action<T>不是.

至于Predicate<T>- 我不知道.

因此,我提出了以下问题:

  1. 怎么Predicate<T>办?(欢迎举例!)
  2. 如果什么都不Action<T>返回,那么使用它会不会更简单?(或任何其他类型,如果我们正在讨论.)voidFunc<T>

我希望你在问题中避免使用LINQ/List示例.
我已经看过那些了但是它们只是让它变得更加混乱,因为让我对这些代表"感兴趣"的代码与它无关(我想!).
因此,我想使用我熟悉的代码来获得我的答案.

这里是:

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

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

public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");

    _execute = execute;
    _canExecute = canExecute;
}

[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
    return _canExecute == null ? true : _canExecute(parameters);
}

public event EventHandler CanExecuteChanged
{
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

public void Execute(object parameters)
{
    _execute(parameters);
}
}
Run Code Online (Sandbox Code Playgroud)

注意:
我拿出了注释以避免超长代码块.
完整的代码可以在这里找到.

任何帮助表示赞赏!谢谢!:)

PS:请不要指我其他问题.我确实试图搜索,但我找不到任何简单的东西让我理解.

SLa*_*aks 9

Predicate<T>是一个代表,取一个T并返回一个bool.
它完全等同于Func<T, bool>.

不同之处在于Predicate<T>.Net 2.0中添加了所有Func<*>代表,而在.Net 3.5中添加了所有代表.(除了具有> 8个参数的那些,在.Net 4.0中添加)

在LINQ状的方法List<T>(FindAll(),TrueForAll()等)采取Predicate<T>秒.

要回答第二个问题,void不能将其用作通用参数.