Func vs. Action vs. Predicate

2

本文介绍了Func vs. Action vs. Predicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有真实的例子和他们的使用,有人可以帮助我理解:

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

  1. 我们什么时候需要 Func 委托?
  2. 我们什么时候需要 Action<T>委托?
  3. 我们什么时候需要 谓词<T>委托?

推荐答案

FuncAction 的区别只是你是否希望委托返回一个值(使用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.BeginInvokeDispatcher.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 代表出现了.我怀疑如果我们已经有各种形式的 FuncAction ,那么 Predicate 就不会被引入......尽管它确实赋予委托的使用某种意义,而 FuncAction 用于广泛不同的目的.

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> 中,用于 FindAllRemoveAll 等方法.

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

这篇关于Func vs. Action vs. Predicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14