namespace Delegate { class 最终 { public delegate string DelNames(string name); static void Main(string[] args) { string[] names = { "wUangWU", "ZhangSan", "LISI" }; OperatorStr(names,(string name) => { name = name.ToUpper();return name; }); Console.ReadKey(); } public static void OperatorStr(string[] names, DelNames dns) { for (int i = 0; i < names.Length; i++) Console.WriteLine(dns(names[i])); } } }
我相信对于没有这方面基础或刚学的人来说很难看懂,没关系,请看下面这个代码你一定看的懂
class 开始 { static void Main(string[] args) { string[] names = { "wUangWU", "ZhangSan", "LISI" }; ToUpperStr(names); //ToLowerStr(names); for (int i = 0; i < names.Length; i++) Console.WriteLine(names[i]); Console.ReadKey(); } public static void ToUpperStr(string[] names) { for (int i = 0; i < names.Length; i++) names[i] = names[i].ToUpper(); } public static void ToLowerStr(string[] names) { for (int i = 0; i < names.Length; i++) names[i] = names[i].ToLower(); } }
}
这是中规中矩的代码,将字符串的大小写转换,再看下三个代码:
class 委托的使用 { public delegate void DelNames(string[] name); static void Main(string[] args) { string[] names = { "wUangWU", "ZhangSan", "LISI" }; DelNames dns = new DelNames(ToUpperStr); DelNames dns1 = new DelNames(ToLowerStr); dns(names); dns1(names); for (int i = 0; i < names.Length; i++) Console.WriteLine(names[i]); Console.ReadKey(); } public static void ToUpperStr(string[] names) { for (int i = 0; i < names.Length; i++) names[i] = names[i].ToUpper(); } public static void ToLowerStr(string[] names) { for (int i = 0; i < names.Length; i++) names[i] = names[i].ToLower(); } }
使用了委托
class 委托的简化V_3 { public delegate string DelNames(string name); static void Main(string[] args) { string[] names = { "wUangWU", "ZhangSan", "LISI" }; //DelNames dns = ToUpperStr; //对这一步的简化 OperatorStr(names, delegate(string name) //加上string的原因是要指明函数的类型,使用的是那种类型的委托 { name = name.ToUpper(); return name; }); //对这步骤的简化,在编译的时候自动new dns的实例化 for (int i = 0; i < names.Length; i++) Console.WriteLine(names[i]); Console.ReadKey(); } public static void OperatorStr(string[] names, DelNames dns) { for (int i = 0; i < names.Length; i++) //对这一步骤的简化,抽象出共同代码部分,实现函数作为参数 names[i] = dns(names[i]); } //使用匿名函数减少代码量,只使用一次的时候,使用匿名函数 } class 委托的简化V_4 { public delegate string DelNames(string name); static void Main(string[] args) { string[] names = { "wUangWU", "ZhangSan", "LISI" }; // DelNames dns =(string name)=> //{ // name = name.ToUpper(); // return name; // }; //对这一步的简化(Lamda表达式和匿名函数的使用) OperatorStr(names, (string name) => { name = name.ToUpper(); return name; }); Console.ReadKey(); } public static void OperatorStr(string[] names, DelNames dns) { for (int i = 0; i < names.Length; i++) //对这一步骤的简化,抽象出共同代码部分,实现函数作为参数 Console.WriteLine(dns(names[i])); } //使用匿名函数减少代码量,只使用一次的时候,使用匿名函数 }
我相信看到这里你应该懂了,快点动手试试