内置泛型类型委托是 C# 中的谓词委托,在命名空间系统下定义。包含特定一组条件的命名空间和方法可以与谓词委托一起使用,以确定传递的参数是否可以满足给定的条件,并且此条件仅采用一个输入,返回值 true 或 false 以及谓词委托与其他委托 Func delegate 和 Action delegate 相同。
语法:
public delegate bool Predicate <in P>(P obj);
其中对象类型由 P 表示,obj 是比较方法内定义的条件并由谓词委托表示的对象。
下面给出了提到的示例:
C# 程序,演示在程序中使用谓词委托来检查作为参数传递的给定字符串是否为大写字母。
代码:
using System; //a namespace called program is defined namespace program { //a class called check is defined public class check { //a Boolean method is defined to check if the given string is written in capital letters or not. If written in capital letters, true is returned else False is returned. static bool IsUC(string stri) { return stri.Equals(stri.ToUpper()); } //main method is called static void Main(string[] args) { //a predicate delegate is defined with object type as string and IsUC is an object which compares the criteria that is defined within a method and is represented by predicate delegate. Predicate<string> isU = IsUC; //The result of the predicate delegate is stored in a variable called res bool res = isU("welcome to c#"); //the result is displayed Console.WriteLine(res); } } }
输出:
说明:
C# 程序,演示在程序中使用谓词委托来检查给定字符串的长度是否小于指定值。
代码:
using System; //a class called program is defined class program { // a predicate delegate is defined with object type as string public delegate bool my_del(string stri); // a method is defined inside a predicate delegate by passing the object as parameter to check if the length of the given string is less than a specified value. If less than the given specified value, true is returned else false is returned public static bool fun(string stri) { if (stri.Length < 5) { return true; } else { return false; } } //Main method is called static public void Main() { // a predicate delegate is defined with object type as string and fun is an object which compares the criteria that is defined within a method and is represented by predicate delegate. my_del obj = fun; //The string to be passed as a parameter to predicate delegate is written here Console.WriteLine(obj("Shobha")); } }
输出:
说明:
以下是 C# Predicate 的优点:
以上是C# 谓词的详细内容。更多信息请关注PHP中文网其他相关文章!