MSDN 定义System.Predicate
this way :
Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
这真的是它的意思,还是它通常用于什么?因为对我来说,它就像一个预定义的delegate
,它的方法必须采用type
T
的object
并返回一个bool
- 仅此而已。
我错过了什么吗?
最佳答案
CLR 不强制类型名称的语义。
所以是的,Predicate<T>
只是一个接受 T
的代表并返回 bool
,但它应该用在需要谓词(对特定条件的测试)的地方。是否尊重该约定取决于程序员。如果你需要一个没有预定义语义的类似委托(delegate),你可以使用 Func<T, bool>
,例如。
对于编译器来说,Predicate<T>
之间没有功能上的区别。或 Func<T, bool>
.但对于阅读您的代码的其他开发人员来说,它提供了一个重要提示,说明您的代码应该做什么,前提是您正确使用了它。
同样,没有什么可以阻止我使用 System.DayOfWeek
存储 1 到 7 之间的任意值,该值实际上并不代表星期几。这将是一件愚蠢的事情,但编译器肯定会让我这样做。确保您的代码有意义取决于您,编译器无法为您完成。
关于c# - System.Predicate<T> : Is this really what it means, 或者这是它的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6758113/