1、什么是委托?
委托就是可以把一个方法作为一个参数带入另一个方法中去。但是委托不是一个方法,而是一种类型。
2、如何使用委托?
在使用委托的时候我们可以像使用一个类一样去实例化它,而与类不同的是。类实例化完成后就是一个对象,而委托实例化后还是一个委托。
3、使用委托的步骤:
例:先声明一个委托
1: ///2: /// 此处声明了一个返回值为空,参数为字符串的委托3: ///4: ///5: public delegate void MyDelegate(string str);
定义一个和委托一样返回值类型和参数类型的方法:
1: public class c2: {3: public static void M1(string str)4: {5: Console.WriteLine("这是第{0}个委托",str);6: }7: public static void M2(string str)8: {9:10: Console.WriteLine("这是第{0}个委托",str);11: }12: }
调用委托实现
1: static void Main(string[] args)2: {3: MyDelegate myDelegate1 = new MyDelegate(c.M1);4: myDelegate1("1");5: MyDelegate myDelegate2 = new MyDelegate(c.M2);6: myDelegate2("2");7: Console.Read();8: }
4、完整代码实现
1: using System;2: using System.Collections.Generic;3: using System.Linq;4: using System.Text;5:6: namespace 委托7: {8:9: class Program10: {11: static void Main(string[] args)12: {13: MyDelegate myDelegate1 = new MyDelegate(c.M1);14: myDelegate1("1");15: MyDelegate myDelegate2 = new MyDelegate(c.M2);16: myDelegate2("2");17: Console.Read();18: }19: ///20: /// 此处声明了一个返回值为空,参数为字符串的委托21: ///22: ///23: public delegate void MyDelegate(string str);24: ///25: ///26: ///27: public class c28: {29: public static void M1(string str)30: {31: Console.WriteLine("这是第{0}个委托",str);32: }33: public static void M2(string str)34: {35:36: Console.WriteLine("这是第{0}个委托",str);37: }38: }39:40: }41: }