C#委托基礎6——泛型委托Predicate
C#委托基礎係列原於2011年2月份發表在我的新浪博客中,現在將其般至本博客。
此委托返回一個bool值,該委托通常引用一個"判斷條件函數"。需要指出的是,判斷條件一般為“外部的硬性條件”,比如“大於50”,而不是由數據自身指定,不如“查找數組中最大的元素就不適合”。
例一
class Program { bool IsGreaterThan50(int i) { if (i > 50) return true; else return false; } static void Main(string[] args) { Program p=new Program(); List<int> lstInt = new List<int>(); lstInt.Add(50); lstInt.Add(80); lstInt.Add(90); Predicate<int> pred = p.IsGreaterThan50; int i = lstInt.Find(pred); // 找到匹配的第一個元素,此處為80 Console.WriteLine("大於50的第一個元素為{0}",i); List<int> all = lstInt.FindAll(pred); for (int j = 0; j < all.Count(); j++) { Console.WriteLine("大於50的數組中元素為{0}", all[j]); // 找出所有匹配條件的 } Console.ReadLine(); } }
例二
class Staff { private double salary; public double Salary { get { return salary; } set { salary = value; } } private string num; public string Num { get { return num; } set { num = value; } } public override string ToString() { return "Num......" + num + "......" + "......" + "Salary......" + salary; } } class Program { bool IsSalaryGreaterThan5000(Staff s) { if (s.Salary > 5000) return true; else return false; } static void Main(string[] args) { Program p = new Program(); List<Staff> allStaff = new List<Staff> { new Staff{Num="001",Salary=9999.9}, new Staff{Num="002",Salary=8991}, new Staff{Num="003",Salary=10000.8}, new Staff{Num="004",Salary=4999.99} }; Predicate<Staff> s = p.IsSalaryGreaterThan5000; Staff theFirstOne = allStaff.Find(s); Console.WriteLine(theFirstOne); // 找出第一個 List<Staff> all = allStaff.FindAll(s); for (int i = 0; i < all.Count(); i++) { Console.WriteLine(all[i]); // 找出所有滿足條件的 } Console.ReadLine(); } }
本文參考自金旭亮老師的《.NET 4.0麵向對象編程漫談》有關代理的內容
最後更新:2017-04-04 07:32:09