標籤:enum foreach string blog var static read key each
委託關鍵詞:delegate
委託是把一個方法當成參數進行傳遞。
先聲明一個委託:兩個參數,返回bool類型
delegate bool Mydelegate(object obj1,object obj2);
委託所對應的方法:
static bool CompareNums(object obj1,object obj2) { return (int)obj1 > (int)obj2; }
擷取最大值的方法:
static object GetMax(object[] objs,Mydelegate mydelegate) { object max = objs[0]; foreach (var item in objs) { if (CompareNums(item, max)) { max = item; } } return max; }
調用方法:
static void Main(string[] args) { object[] nums = {1,2,3,4,5,0 }; Mydelegate mydel = new Mydelegate(CompareNums); object max = GetMax(nums, mydel); Console.WriteLine(max); Console.ReadKey(); }
========由於擷取最大值的方法只用到一次,可以使用匿名方法來代替,這樣會更簡潔=======
static void Main(string[] args) { object[] nums = {1,2,3,4,5,0 }; Mydelegate mydel = delegate (object obj1, object obj2) { return (int)obj1 > (int)obj2; }; object max = GetMax(nums, mydel); Console.WriteLine(max); Console.ReadKey(); }
=================由於系統內建Action和Func兩種委託,所以沒必要去自訂委託啦=================
Action委託傳回值為void
Func有傳回值
擷取最大值方法改造為:
static object GetMax(object[] objs,Func<object,object,bool>func) { object max = objs[0]; foreach (var item in objs) { if (CompareNums(item, max)) { max = item; } } return max; }
方法調用改造為:
static void Main(string[] args) { object[] nums = {1,2,3,4,5,0 }; Func<object,object,bool> func= delegate (object obj1, object obj2) { return (int)obj1 > (int)obj2; }; object max = GetMax(nums, func); Console.WriteLine(max); Console.ReadKey(); }
=================使用lambda進行簡化====================
static void Main(string[] args) { object[] nums = {1,2,3,4,5,0 }; Func<object, object, bool> func = (obj1, obj2) => { return (int)obj1 > (int)obj2; }; object max = GetMax(nums, func); Console.WriteLine(max); Console.ReadKey(); }
C#委託,匿名函數,lambda的演變