<分区>
通过真实的例子和它们的使用,有人可以帮助我理解:
- 我们什么时候需要
Func<T, ..>
委托(delegate)? - 我们什么时候需要
Action<T>
委托(delegate)? - 我们什么时候需要
Predicate<T>
委托(delegate)?
<分区>
通过真实的例子和它们的使用,有人可以帮助我理解:
Func<T, ..>
委托(delegate)?Action<T>
委托(delegate)?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)们也来了。我怀疑如果我们已经有了 Func
和 Action
以各种形式,Predicate
不会被引入...虽然它确实赋予委托(delegate)的使用一定的意义,而Func
和 Action
用于广泛不同的目的。
Predicate
主要用于 List<T>
对于类似 FindAll
的方法和 RemoveAll
.
关于c# - Func vs. Action vs. Predicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317479/