FUNC主场迎战主场迎战行动predicate [英] Func vs. Action vs. Predicate
问题描述
通过实际例子和它们的使用,有人可以帮我明白了:
- 当我们需要Func键代表?
- 当我们需要Action委托?
- 当我们需要predicates代表?
Func键之间的区别
和动作
是您只需是否要委托返回一个值(使用函数功能
)或不(使用动作
)。
函数功能
可能是最常使用LINQ - 例如在预测:
list.Select(X => x.SomeProperty)
或过滤:
list.Where(X => x.SomeValue == someOtherValue)
或键选择:
list.Join(otherList,X => x.FirstKey,Y => y.SecondKey,...)
动作
更常用的如的事情列表< T> .ForEach
:执行每个给定的动作列表中的项目。我用这往往小于函数功能
,虽然我的做的有时会使用的东西无参数的版本,如 Control.BeginInvoke
和 Dispatcher.BeginInvoke
。
predicate
只是一个特殊的套管 Func键< T,BOOL>
真的,所有的前出台在函数功能
和大多数行动
代表来了。我怀疑,如果我们就已经有了函数功能
和动作
在他们的各种名目, predicate
将不会被引入......虽然它的确实的传授一定的意义的使用委托的,而函数功能
和动作
用于广泛不同的目的。
predicate
在主要用于名单< T>
像方法的FindAll
和 removeall过
。
With real examples and their use, can someone please help me understand:
- When do we need Func delegate?
- When do we need Action delegate?
- When do we need Predicates delegate?
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
这篇关于FUNC主场迎战主场迎战行动predicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!