Action<T>, Func<T> and Predicate<T>
作为我的 WPF/MVVM 学习的一部分,我试图了解代表之间的差异。
我知道Action<T> and Func<T>
两者都采用零到一个+参数,只Func<T>
返回一个值而Action<T>
不是。
至于Predicate<T>
——我不知道。
因此,我提出了以下问题:
- 做什么
Predicate<T>
?(欢迎举例!) - 如果没有
Action<T>
返回,那么使用它不是更简单吗?(或者任何其他类型,如果它是我们正在谈论的。)void
Func<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);
}
}
注意:
我去掉了注释以避免超长的代码块。
完整的代码可以在这里找到。
任何帮助表示赞赏!谢谢!:)
PS:请不要指点我其他问题。我确实尝试过搜索,但找不到足够简单的东西让我理解。