委托就是第三方,调用者告诉第三方要做什么,然后调用者就不用管了 这个委托(第三方)就会去调用方法去帮你实现
委托的好处:
1.相当于用方法作为另一方法参数(类似于C的函数指针)
2.在两个不能直接调用的方法中作为桥梁,如:在多线程中的跨线程的方法调用就得用委托
3.当不知道方法具体实现什么时使用委托,如:事件中使用委托
先看个例子,中国人打招呼,和英国人打招呼的一般写法
static void Main(string[] args) { SayHiChinese("Jim"); SayHiEnglish("Jim"); Console.Read(); } public static void SayHiChinese(string name) { Console.WriteLine("吃饭了吗 {0}",name); } public static void SayHiEnglish(string name) { Console.WriteLine("Nice to meet you {0}",name); }
再看下委托
//定义一个委托 public delegate void SayHi(string name); static void Main(string[] args) { //SayHi SHZh = new SayHi(SayHiChinese); SayHi SHZh = SayHiChinese; SHZh("Jim"); //SayHi SHEn = new SayHi(SayHiEnglish); SayHi SHEn = SayHiEnglish; SHEn("Jim"); Console.Read(); } public static void SayHiChinese(string name) { Console.WriteLine("吃饭了吗 {0}",name); } public static void SayHiEnglish(string name) { Console.WriteLine("Nice to meet you {0}",name); }
或者
//定义一个委托 public delegate void SayHi(string name); static void Main(string[] args) { test("Jim", SayHiChinese); test("Jim", SayHiEnglish); Console.Read(); } private static void test(string name, SayHi SH) { SH(name); } public static void SayHiChinese(string name) { Console.WriteLine("吃饭了吗 {0}",name); } public static void SayHiEnglish(string name) { Console.WriteLine("Nice to meet you {0}",name); }
结果都是
匿名函数
//定义一个委托 public delegate void SayHi(string name); static void Main(string[] args) { SayHi SH = delegate (string name) { Console.WriteLine("你好 "+ name); }; SH("Jim"); Console.Read(); }
lamda表达式
//定义一个委托 public delegate void SayHi(string name); static void Main(string[] args) { SayHi SH = (string name) => { Console.WriteLine("你好"+name); }; SH("Jim"); Console.Read(); }