C#中委托是什么?事件是委托吗?
1.委托是讲方法作为参数代入另一个方法中, 委托可以理解为指向一个函数的引用。
class Program { public delegate void DelegateGreeting(string sName); // 步骤1,声明delegate对象z static void Main(string[] args) { Console.WriteLine("输出结果是:"); DelegateGreeting du = new DelegateGreeting(Program.MakeGreet); // 步骤2,创建DelegateUtil对象 du("I'm learning delegate now !");// 步骤3,调用DelegateUtil Console.ReadLine(); } /// <summary> /// 描述:这是想要传递的方法,该方法与定义的委托(即DelegateUtil)具有相同的参数和返回值类型,函数名是不一样的哦! /// </summary> /// <param name="sName"></param> public static void MakeGreet(string sName) { Console.WriteLine("Hi, " + sName); } }
输出:
Hi,I'm learning delegate now !
注:参数不一样是,声明委托时参数也不一样
class Program { public delegate void DelegateGreeting(string sName,Language lan); // 步骤1,声明delegate对象z static void Main(string[] args) { Console.WriteLine("输出结果是:"); DelegateGreeting du = new DelegateGreeting(Program.PeopelGreet); // 步骤2,创建DelegateUtil对象 du("xiaoming",Language.English);// 步骤3,调用DelegateUtil Console.ReadLine(); } /// <summary> /// 描述:这是想要传递的方法,该方法与定义的委托(即DelegateUtil)具有相同的参数和返回值类型,函数名是不一样的哦! /// </summary> /// <param name="sName"></param> public static void PeopelGreet(string sName, Language lan) { switch (lan) { case Language.English: { Console.WriteLine("Morning, " + sName); break; } case Language.Chinese: { Console.WriteLine("早上好, " + sName); break; } } } } public enum Language { English, Chinese }
输出:
输出结果是:
Morning,xiaoming
待续。。。。
http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx
http://www.cnblogs.com/xlx0210/archive/2010/08/08/1794959.html