-1

以下のサンプルでは、​​a を使用してpredicate、ハードコードされた値 100000 の条件を評価しています。メソッドにパラメーターを追加する方法はありませんFindPoints。述語パラメーターの制約に違反するためです。

これにより、述語を使用する価値が疑問視されます。明らかに、ラムダはこの問題を解決します..しかし、それでもなお、この一見奇妙な制約を考えると、実際のシナリオでの述語の有用性について詳しく説明できる人はいますか?

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

編集: 同じことを行うためのラムダの使用法を以下に示します。

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からのものです。この記事は良い例を示していますが、私の質問には答えていないようです。

4

1 に答える 1