有真实的例子和他们的使用,有人可以帮助我理解:
With real examples and their use, can someone please help me understand:
Func 委托?
Action<T>
委托?谓词<T>
委托?Func
和 Action
的区别只是你是否希望委托返回一个值(使用Func
) 与否(使用 Action
).
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
可能是 LINQ 中最常用的——例如在投影中:
Func
is probably most commonly used in LINQ - for example in projections:
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
.
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
实际上只是一个特殊的 Func
,在所有 Func
和大部分 之前引入>Action
代表出现了.我怀疑如果我们已经有各种形式的 Func
和 Action
,那么 Predicate
就不会被引入......尽管它确实赋予委托的使用某种意义,而 Func
和 Action
用于广泛不同的目的.
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
主要用于 List<T>
中,用于 FindAll
和 RemoveAll
等方法.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
这篇关于Func vs. Action vs. Predicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!