委托


delegate

委托

将一个方法作为参数传递给另一个方法

委托所指明的函数必须和委托有相同的签名(参数,返回值)

 1 public delegate string DelProStr(string name);
 2         static void Main(string[] args)
 3         {
 4             string[] name = { "AJDdsjdn","jsbjNDJA","NDSJndjsJ","NDJSnds" };
 5             ProStr(name,GetMax);
 6 或者:DelProStr del=GetMax;
 7 del(name);
 8             for (int i = 0; i < name.Length; i++)
 9             {
10                 Console.WriteLine(name[i]);
11             }
12         }
13         public static void ProStr(string[] name,DelProStr del)
14         {
15             for (int i = 0; i < name.Length; i++)
16             {
17                 name[i] = del(name[i]);
18             }
19         }
20         public static string GetMax(string name)
21         {
22             return name.ToUpper();
23         }
24         public static string GetMini(string name)
25         {
26             return name.ToLower();
27         }
28         public static string StrShy(string name)
29         {
30             return "\"" + name + "\"";
31         }
32 }

匿名函数:当方法就执行一次的时候,可以写成匿名函数,这样就不需要单独的方法,直接在调用的时候写一个方法体

 1 例1.
 2 public delegate string DelProStr(string name);
 3         static void Main(string[] args)
 4         {
 5             string[] name = { "AJDdsjdn", "jsbjNDJA", "NDSJndjsJ", "NDJSnds" };
 6             ProStr(name, delegate (string name)
 7              {
 8                  return name.ToUpper();
 9              });
10             for (int i = 0; i < name.Length; i++)
11             {
12                 Console.WriteLine(name[i]);
13             }
14         }
15         public static void ProStr(string[] name, DelProStr del)
16         {
17             for (int i = 0; i < name.Length; i++)
18             {
19                 name[i] = del(name[i]);
20             }
21         }
 1 public delegate int DelCompare(object o1, object o2);
 2 class Program
 3     {
 4         static void Main(string[] args)
 5         {
 6             object[] nums = { 1, 2, 3, 4, 5, 6 };
 7             object[] str = { "dsdssd", "dADADASDASDADDDSASDA", "sa" };
 8             object o=GetMax(str, delegate (object o1, object o2)
 9              {
10                  /*int n1 = (int)o1;
11                  int n2 = (int)o2;
12                  return n1 - n2;*/
13                  string s1 = (string)o1;
14                  string s2 = (string)o2;
15                  return s1.Length - s2.Length;
16              });
17             Console.WriteLine(o);
18         }
19         public static object GetMax(object[] nums, DelCompare del)
20         {
21             object max = nums[0];
22             for (int i = 0; i < nums.Length; i++)
23             {
24                 if (del(max,nums[i])<0)
25                 {
26                     max = nums[i];
27                 }
28             }
29             return max;
30         }
31     }