Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c# - Func vs. Action vs. Predicate [复制](Func vs. Action vs. Predicate [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

With real examples and their use, can someone please help me understand:

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

  1. When do we need Func delegate?

    (我们什么时候需要Func委托?)

  2. When do we need Action delegate?

    (我们什么时候需要行动委托?)

  3. When do we need Predicates delegate?

    (我们什么时候需要Predicates委托?)

  ask by InfoLearner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The difference between Func and Action is simply whether you want the delegate to return a value (use Func ) or not (use Action ).

(FuncAction之间的区别仅在于您是否希望委托返回值(使用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.BeginInvokeDispatcher.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.

(我怀疑,如果我们已经有各种伪装的FuncAction ,那么Predicate就不会被引入......尽管它确实赋予了代表使用某种意义,而FuncAction则被广泛地使用了目的。)

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll .

(Predicate主要用于List<T>用于FindAllRemoveAll等方法。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...