下面的示例显示使用 apredicate
来评估硬编码值为 100000 的条件。无法向该FindPoints
方法添加其他参数,因为它会违反谓词参数约束。
这使使用谓词的价值受到质疑。显然 Lambda 解决了这个问题..但是,鉴于这个看似奇怪的约束,任何人都可以详细说明谓词在现实生活场景中的有用性。
如果他们不接受 T 以外的参数,为什么有人会使用谓词?
using System;
using System.Drawing;
public class Example
{
public static void Main()
{
// Create an array of Point structures.
Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
// Define the Predicate<T> delegate.
Predicate<Point> predicate = FindPoints;
// Find the first Point structure for which X times Y
// is greater than 100000.
Point first = Array.Find(points, predicate);
// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
}
private static bool FindPoints(Point obj)
{
return obj.X * obj.Y > 100000;
}
}
// The example displays the following output:
// Found: X = 275, Y = 395
编辑:使用 Lambda 来做同样的事情,如下。
using System;
using System.Drawing;
public class Example
{
public static void Main()
{
// Create an array of Point structures.
Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
// Find the first Point structure for which X times Y
// is greater than 100000.
Point first = Array.Find(points, x => x.X * x.Y > 100000 );
// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
}
}
// The example displays the following output:
// Found: X = 275, Y = 395
这是来自MSDN。这篇文章给出了很好的例子,但似乎没有解决我的问题。