c# - Func vs. Action vs. Predicate

标签 c# delegates action func

<分区>

通过真实的例子和它们的使用,有人可以帮助我理解:

  1. 我们什么时候需要 Func<T, ..> 委托(delegate)?
  2. 我们什么时候需要 Action<T> 委托(delegate)?
  3. 我们什么时候需要 Predicate<T> 委托(delegate)?

最佳答案

Func之间的区别和 Action只是您是否希望委托(delegate)返回一个值(使用 Func )或不返回(使用 Action )。

Func可能在 LINQ 中最常用 - 例如在投影中:

 list.Select(x => x.SomeProperty)

或过滤:

 list.Where(x => x.SomeValue == someOtherValue)

或按键选择:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action更常用于 List<T>.ForEach 之类的东西:对列表中的每个项目执行给定的操作。我使用它的频率低于 Func ,尽管我确实有时会为 Control.BeginInvoke 之类的东西使用无参数版本和 Dispatcher.BeginInvoke .

Predicate只是一个特例 Func<T, bool>真的,之前介绍的都是Func和大部分 Action委托(delegate)们也来了。我怀疑如果我们已经有了 FuncAction以各种形式,Predicate不会被引入...虽然它确实赋予委托(delegate)的使用一定的意义,而FuncAction用于广泛不同的目的。

Predicate主要用于 List<T>对于类似 FindAll 的方法和 RemoveAll .

关于c# - Func vs. Action vs. Predicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317479/

相关文章:

c# - C# 中的复选框数组

c# - 加载javascript和速度问题

c# - 异步多播委托(delegate)

ios - 加载 UIView 时 exc_bad_access code=1

javascript - 如何测试 redux 操作中抛出的错误

node.js - 如何使用对话流从 RESTful API 获取数据

c# - C#/.net 3.5SP1 中线程的基本架构和生命周期

C# String.Format - 无效的输入字符串

.net - c# 中事件和委托(delegate)的替代方法是什么?

javascript - 在其中添加额外代码后,删除操作不起作用