C#谓词委托用法介绍

2021年5月8日16:24:32 发表评论 675 次浏览

谓词委托是内置的泛型类型代表。该委托在系统命名空间。它与那些包含一些标准并确定传递的参数是否满足给定标准的方法一起使用。该委托仅接受一个输入, 并以true或false的形式返回值。现在, 首先, 我们了解自定义委托在这种情况下的工作方式。如下例所示。

语法如下:

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

在这里, P是对象的类型, 对象是要与Predicate代表的方法中定义的标准进行比较的对象。

例子:

//C# program to illustrate delegates
using System;
  
class GFG {
  
     //Declaring the delegate
     public delegate bool my_delegate( string mystring);
  
     //Method
     public static bool myfun( string mystring)
     {
         if (mystring.Length <7) 
         {
             return true ;
         }
  
         else
         {
             return false ;
         }
     }
  
     //Main method
     static public void Main()
     {
  
         //Creating object of my_delegate
         my_delegate obj = myfun;
         Console.WriteLine(obj( "Hello" ));
     }
}

输出如下:

True

现在, 我们将上述程序与谓词委托一起使用, 如下所示。

例子:在下面的示例中, 我们使用谓词委托而不是自定义委托。它减少了代码的大小, 并使程序更具可读性。在此, 谓词委托包含单个输入参数, 并以布尔类型返回输出。在这里, 我们直接分配一个Myfun谓词委托的方法。

//C# program to illustrate Predicate delegates
using System;
  
class GFG {
  
     //Method
     public static bool myfun( string mystring)
     {
         if (mystring.Length <7)
         {
             return true ;
         }
         else 
         {
             return false ;
         }
     }
  
     //Main method
     static public void Main()
     {
  
         //Using predicate delegate
         //here, this delegate takes
         //only one parameter
         Predicate<string> val = myfun;
         Console.WriteLine(val( "lsbin" ));
     }
}

输出如下:

False

重要事项:

你还可以将Predicate委托与匿名方法一起使用, 如以下示例所示:

例子:

Predicate<string> val = delegate ( string str)
{
     if (mystring.Length <7)
     {
         return true ;
     }
     else 
     {
         return false ;
     };
     val( "Geeks" );

你还可以将谓词委托与lambda表达式一起使用, 如以下示例所示:

例子:

Predicate<string> val = str => str.Equals(str.ToLower());
val( "Geeks" );

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: