C#中谓词和Func委托之间的区别 [英] differences between Predicate and Func delegate in C#

查看:93
本文介绍了C#中谓词和Func委托之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的初学者,只是一个关于C#中的谓词和Func委托之间的区别的问题

I'm a beginner in C#, just a question on differences between Predicate and Func delegate in C#

我们知道:

public delegate bool Predicate<in T>(T obj);

public delegate TResult Func<in T, out TResult>(T arg);

所以,如果我喜欢

Func<Product, bool> firstdelegate = ...

Predicate<Product> secondpredicate = ...

它们不一样吗?我是说它们都做同样的事情,所以为什么要在LINQ的Where()方法中使用Func类型委托而不是谓词呢?

aren't they the same? I mean they all do the same thing, so why in LINQ' Where() method takes Func type delegate instead of Predicate?

推荐答案

谓词T< code> 是在.NET 2.0中引入泛型的。这是一个接受一个参数并返回 bool 的委托。

Predicate<T> was introduced in .NET 2.0 with the introduction of generics. It's a delegate taking one parameter and returning a bool.

不过,.NET 3.5中引入了LINQ ,则确定需要两个通用类型的家族- Func Action (区别在于它们是否返回任何东西)最多占用 16 4 1 个通用输入参数,并且在返回类型上是通用的。如果先存在 Func ,则首先不会创建 Predicate< T>

However, with the introduction of LINQ in .NET 3.5, a need was identified for two families of generic types - Func and Action (the difference being on whether they return anything) taking up to 16 41 generic input parameters and being generic in their return types. If Func had existed first, Predicate<T> would never have been created in the first place. It's an unnecessarily specialized delegate type.

尽管出于向后兼容的原因,它们现在不能删除 Predicate< T> 有些可能会争辩说它的名称确实传达了特定的语义含义,但我很难确定许多情况,其中任何 Func< T,bool> (或 Func< T1,T2,bool> 等)不被视为谓词。

For backwards compatibility reasons though, they cannot now remove Predicate<T> from the framework. Some may argue that it's name does convey specific semantic meaning but I'd struggle to identify many situations where any Func<T,bool> (or Func<T1,T2,bool>, etc) wouldn't be considered a predicate.

1 4,.NET 4及更高版本中的16。

14 in .NET 3.5, 16 in .NET 4 and later.

这篇关于C#中谓词和Func委托之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆