代表:Predicate Action Func

129 c# delegates

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

  • 谓语
  • 行动
  • FUNC

C#开发人员应该注意哪些其他代表?

您多久在生产代码中使用它们?

Jon*_*eet 177

  • Predicate:基本上Func<T, bool>; 问一个问题"指定的参数是否满足委托所代表的条件?" 用于像List.FindAll这样的东西.

  • Action:根据参数执行操作.非常通用.在LINQ中使用不多,因为它基本上意味着副作用.

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

其他重要代表:

  • EventHandler/ EventHandler<T>:遍布WinForms

  • Comparison<T>:喜欢IComparer<T>但是以代表的形式.

  • 当需要将大量模型转换为业务类时,转换器是一个很好的代表,即http://www.stum.de/2009/12/23/using-a-converter-to-convert-from-a-模型到一个企业级/ (4认同)
  • 还有`System.Converter <TInput,TOutput>`,尽管它很少使用. (3认同)

Rah*_*arg 40

Action,Func并且Predicate都属于委托家人.

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

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

Predicate:谓词也是Func的一种形式,但它总会返回bool.简单来说就是它的包装Func<T,bool>.


G-W*_*Wiz 9

除了Jon的回答,还有

  • Converter<TInput, TOutput>:它本质上是Func<TInput, TOutput>,但有语义.由List.ConvertAll和Array.ConvertAll使用,但个人还没有在其他任何地方看到它.


dim*_*ath 5

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

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

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

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

Func<string> print = () => "Hello world";
Console.WriteLine(print());//Print Hello world
Run Code Online (Sandbox Code Playgroud)

此操作采用两个 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
Run Code Online (Sandbox Code Playgroud)

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

Predicate<int> isPositive = (x) => x > 0;
Console.WriteLine(isPositive(5));//Print True
Run Code Online (Sandbox Code Playgroud)