The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
(Func
和Action
之间的区别仅在于您是否希望委托返回值(使用Func
)或不使用(使用Action
)。)
Func
is probably most commonly used in LINQ - for example in projections:
(Func
可能是LINQ中最常用的 - 例如在投影中:)
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.
(Action
更常用于List<T>.ForEach
:对列表中的每个项执行给定的操作。)
I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
. (我用这个少往往比Func
,虽然我有时会使用,例如,无参数的版本Control.BeginInvoke
和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.
(Predicate
只是一个特殊的套装Func<T, bool>
真的,在所有Func
和大多数Action
代表出现之前引入。)
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. (我怀疑,如果我们已经有各种伪装的Func
和Action
,那么Predicate
就不会被引入......尽管它确实赋予了代表使用某种意义,而Func
和Action
则被广泛地使用了目的。)
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
(Predicate
主要用于List<T>
用于FindAll
和RemoveAll
等方法。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…