C# 委托:谓词 vs. 动作 vs. 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/566860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:28:03  来源:igfitidea点击:

Delegates: Predicate vs. Action vs. Func

c#delegatespredicatefunc

提问by

Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:

有人可以为这 3 个最重要的代表提供一个很好的解释(希望有例子):

  • Predicate
  • Action
  • Func
  • 谓词
  • 行动
  • 功能

采纳答案by Jon Skeet

  • Predicate: essentially Func<T, bool>; asks the question "does the specified argument satisfy the condition represented by the delegate?" Used in things like List.FindAll.

  • Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.

  • Func: Used extensivelyin LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.

  • Predicate:本质Func<T, bool>; 提出问题“指定的参数是否满足委托所表示的条件?” 用于 List.FindAll 之类的东西。

  • Action: 执行给定参数的操作。非常通用的用途。在 LINQ 中使用不多,因为它基本上意味着副作用。

  • Func:在 LINQ 中广泛使用,通常用于转换参数,例如通过将复杂结构投影到一个属性。

Other important delegates:

其他重要代表:

  • EventHandler/EventHandler<T>: Used all over WinForms

  • Comparison<T>: Like IComparer<T>but in delegate form.

  • EventHandler/ EventHandler<T>: 在 WinForms 中使用

  • Comparison<T>: 喜欢,IComparer<T>但以委托形式。

回答by G-Wiz

In addition to Jon's answer, there is also

除了乔恩的回答,还有

  • Converter<TInput, TOutput>: It's essentially Func<TInput, TOutput>, but with semantics. Used by List.ConvertAll and Array.ConvertAll, but personally haven't seen it anywhere else.
  • Converter<TInput, TOutput>: 它本质上是Func<TInput, TOutput>,但有语义。由 List.ConvertAll 和 Array.ConvertAll 使用,但个人在其他任何地方都没有见过。

回答by El Zorko

MethodInvoker is one which WinForms developers may use; it accepts no arguments and returns no results. It predates Action, and is still often used when invoking onto the UI thread since BeginInvoke() et al accept an untyped Delegate; although Action will do just as well.

MethodInvoker 是 WinForms 开发人员可以使用的一种;它不接受任何参数并且不返回任何结果。它早于 Action,并且在调用 UI 线程时仍然经常使用,因为 BeginInvoke() 等人接受无类型委托;尽管 Action 也一样。

myForm.BeginInvoke((MethodInvoker)delegate
{
  MessageBox.Show("Hello, world...");
});

I'd also be aware of ThreadStart and ParameterizedThreadStart; again most people will substitute an Action these days.

我也会知道 ThreadStart 和 ParameterizedThreadStart;再一次,如今大多数人会用 Action 来替代。

回答by IntelligentBinary

Predicate, Func and Action are inbuilt delegate instances of .NET. Each of these delegate instances could refer or point to user methods with specific signature.

Predicate、Func 和 Action 是 .NET 的内置委托实例。这些委托实例中的每一个都可以引用或指向具有特定签名的用户方法。

Action delegate - Action delegate instances could point to methods that take arguments and returns void.

动作委托 - 动作委托实例可以指向接受参数并返回 void 的方法。

Func delegate - Func delegate instance could point to method(s) that take variable number of arguments and return some type.

Func 委托 - Func 委托实例可以指向采用可变数量参数并返回某种类型的方法。

Predicate - Predicates are similar to func delegate instances and they could point to methods that take variable number of arguments and return a bool type.

谓词 - 谓词类似于 func 委托实例,它们可以指向采用可变数量参数并返回 bool 类型的方法。

回答by Rahul Garg

Action, Funcand Predicateall belong to the delegate family.

ActionFunc并且Predicate都属于委托家族。

Action: Action can take n input parameters but it returns void.

Action: Action 可以接受 n 个输入参数,但它返回 void。

Func: Func can take n input parameters but it will always return the result of the provided type. Func<T1,T2,T3,TResult>, here T1,T2,T3 are input parameters and TResult is the output of it.

Func: Func 可以接受 n 个输入参数,但它将始终返回所提供类型的结果。Func<T1,T2,T3,TResult>, 这里 T1,T2,T3 是输入参数,TResult 是它的输出。

Predicate: Predicate is also a form of Func but it will always return bool. In simple words it is wrapper of Func<T,bool>.

Predicate: Predicate 也是 Func 的一种形式,但它总是返回 bool。简单来说,它是Func<T,bool>.

回答by Rahul Garg

Action and Func with lambda:

带有 lambda 的 Action 和 Func:

person p = new person();
Action<int, int> mydel = p.add;       /*(int a, int b) => { Console.WriteLine(a + b); };*/
Func<string, string> mydel1 = p.conc; /*(string s) => { return "hello" + s; };*/
mydel(2, 3);
string s1=  mydel1(" Akhil");
Console.WriteLine(s1);
Console.ReadLine();

回答by Rm558

Func is more LINQ friendly, can be passed in as a parameter. (point-free)

Func 对 LINQ 更友好,可以作为参数传入。(无积分)

Predicate cannot, has to be wrapped again.

谓词不能,必须重新包装。

Predicate<int> IsPositivePred = i => i > 0;
Func<int,bool> IsPositiveFunc = i => i > 0;

new []{2,-4}.Where(i=>IsPositivePred(i)); //Wrap again

new []{2,-4}.Where(IsPositivePred);  //Compile Error
new []{2,-4}.Where(IsPositiveFunc);  //Func as Parameter

回答by dimath

A simple example about the arguments and what retutn each type

关于参数和每种类型的返回内容的简单示例

This Func take two int arguments and return an int.Func always has return type

这个 Func 接受两个 int 参数并返回一个 int.Func 总是有返回类型

 Func<int, int, int> sum = (a, b) => a + b;
 Console.WriteLine(sum(3, 5));//Print 8

In this case func doesn't have arguments but return a string

在这种情况下 func 没有参数但返回一个字符串

Func<string> print = () => "Hello world";
Console.WriteLine(print());//Print Hello world

This Action take two int arguments and return void

此操作采用两个 int 参数并返回 void

Action<int, int> displayInput = (x, y) => Console.WriteLine("First number is :" + x + " , Second number is "+ y);
displayInput(4, 6); //Print First number is :4 , Second number is :6

This Predicate take one argument and always return bool.Generally Predicates always return bool.

这个谓词接受一个参数并且总是返回bool。一般来说谓词总是返回bool。

Predicate<int> isPositive = (x) => x > 0;
Console.WriteLine(isPositive(5));//Print True