简体   繁体   English

FUNC <TObject, bool> 或谓词 <TObject> ?

[英]Func<TObject, bool> or Predicate<TObject>?

I've seen time and time again API (particularly in the .NET framework) that uses Func<TObject, bool> when Predicate<TObject> is seemingly a perfectly responsible option. 我一次又一次地看到API(特别是在.NET框架中)使用Func<TObject, bool>Predicate<TObject>看起来是一个完全负责任的选项。 What good reasons might an API designer have for doing so? API设计师可能有什么好的理由呢?

In LINQ, Func<T, bool> is used for things like Where so that the other overload which takes the index as well as the element is consistent: 在LINQ中, Func<T, bool>用于Where之类的东西,以便获取索引和元素的另一个重载是一致的:

IEnumerable<T> Where(IEnumerable<T> source, Func<T, bool> predicate)
IEnumerable<T> Where(IEnumerable<T> source, Func<T, int, bool> predicate)

Personally I think the name Predicate is more descriptive, so I would use it in situations where there's no consistency issue like the one above. 我个人认为名称Predicate更具描述性,所以会在没有像上面那样的一致性问题的情况下使用它。 Mind you, there's something to be said for only needing to know about the Action and Func delegate types... 请注意,只需要知道ActionFunc委托类型就可以说了些什么......

Consistency with the rest of LINQ? 与LINQ其余部分保持一致?

(The "anomaly" has been noted, but with anonymous delegates and lambda functions it makes no difference, so almost never need to be aware of the difference.) (已经注意到“异常”,但是使用匿名委托和lambda函数它没有区别,所以几乎从不需要意识到差异。)

The Func<> delegates are the "new" way of specifying lambdas/delegates to methods. Func <>委托是指定方法的lambdas / delegates的“新”方法。 However, there just a handy set of delegates, and if there's a more specific delegate that does the same thing then go for that. 但是,只有一组方便的委托,如果有一个更具体的委托做同样的事情,那么就去做。

In your example I'd always go for the Predicate<> as it's much more self-documenting (assuming a predicate is what you want) 在你的例子中,我总是选择Predicate <>,因为它更自我记录(假设谓词是你想要的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM