內建泛型類型委託是 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中文網其他相關文章!