委托是一个类,定义了方法的类型,使一个方法可以作为另一个方法的参数传递,程序具有更好的可扩展性。
举个栗子,有一家红娘机构,提供委托找对象的服务,其中有一个服务套餐叫ObjectClassDelegate,可以指定身高和收入,回去之后红娘找到了再告诉你有几个符合你的要求。
protected delegate int ObjectClassDelegate(int height, int salary); static void Main() { #region Delegate自定义 ObjectClassDelegate dele = new ObjectClassDelegate(FindObject); int count = AfterBye(dele,165, 15000);//传入委托以调用方法 #endregion Delegate自定义 #region Func 必须有返回值 Func<int, int, int> fc = FindObject; int result = AfterBye(fc, 165, 15000);#endregion #region Action 无返回值 Action<int, int> go_between = (height, salary) => Console.WriteLine($"我帮你留意身高{height},收入{salary}的。"); AfterBye(go_between,165,15000); #endregion } static int AfterBye(ObjectClassDelegate fc, int height, int salary) { return fc(height, salary); } static int AfterBye(Func<int, int, int> fc, int height, int salary) { return fc(height, salary); } static void AfterBye(Action<int, int> findObject, int height, int salary) { findObject(height, salary); } static int FindObject(int height, int salary) { if (height >= 160 && height <= 165 && salary > 15000) { return 2; } else if (height > 165 && height <= 170 && salary > 15000) { return 1; } else { return 0; } }
标签:salary,委托,int,fc,AfterBye,height,如何,理解,static From: https://www.cnblogs.com/GZ-Blog/p/17903857.html