委托和事件是.net程序设计中一个难度中等、重要性高等的知识点,掌握好委托和事件,是一个中级程序员的标识之一。
不说废话,直接上代码,要看效果请建立一个控制台程序,然后把下面代码拷贝并替换Program类。

/**//* *************************************
* 公司:浙江新能量科技有限公司
* 网站:http://www.freshpower.com.cn
* 电力商务网:http://www.freshpower.cn
* ------------------------------------
* 作者:李中华 lizhh@freshpower.cn
* 日期:2008-7-2
* *************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CEDU


{
delegate void TestDelegate1();
delegate void TestDelegate2(string msg);
delegate void TestDelegate3(string msg, int i);
class Program

{
//C#1.0:定义事件
static event TestDelegate1 td1;
//C#2.0:定义事件
static event TestDelegate1 td2;
//C#3.0:定义事件
static event TestDelegate1 td3;

static void Main(string[] args)

{
InitEvent();
TM1();
TM2("带参数的测试");
TM3("带参数的测试", 0);
Console.ReadKey();
}

与事件有关的成员#region 与事件有关的成员
static void InitEvent()

{
td1 += new TestDelegate1(Program_td1);

td2 = delegate()
{ Console.WriteLine("---------------OVER2---------------"); };

td3 = () =>
{ Console.WriteLine("---------------OVER3---------------"); };
}

static void Ontd1()

{
if (td1 == null) return;
td1();
}
static void Ontd2()

{
if (td2 == null) return;
td2();
}
static void Ontd3()

{
if (td3 == null) return;
td3();
}

static void Program_td1()

{
Console.WriteLine("---------------OVER1---------------");
}
#endregion


委托1有关的成员#region 委托1有关的成员
static void TM1()

{
//C#1.0
TestDelegate1 t1 = new TestDelegate1(M1);
//C#2.0

TestDelegate1 t2 = delegate()
{ Console.WriteLine("C#2.0的委托的输出 匿名委托"); };
//C#3.0

TestDelegate1 t3 = () =>
{ Console.WriteLine("C#3.0的委托输出 Lambdab表达式"); };

t1();
Ontd1();//激发事件
t2();
Ontd2();//激发事件
t3();
Ontd3();//激发事件
}
static void M1()

{
Console.WriteLine("C#1.0的委托的输出");
}
#endregion


委托2有关的成员#region 委托2有关的成员
static void TM2(string msg)

{
TestDelegate2 t1 = new TestDelegate2(M2);

TestDelegate2 t2 = delegate(string msg2)
{ Console.WriteLine("C#2.0的委托的输出 匿名委托,{0}", msg2); };
TestDelegate2 t3 = msg3 => Console.WriteLine("C#3.0的委托输出 Lambdab表达式,{0}", msg3);

t1(msg);
t2(msg);
t3(msg);
}
static void M2(string msg)

{
Console.WriteLine("C#1.0的委托的输出 {0}", msg);
}
#endregion


委托3有关的成员#region 委托3有关的成员
static void TM3(string msg,int i)

{
TestDelegate3 t1 = new TestDelegate3(M3);

TestDelegate3 t2 = delegate(string msg2, int i2)
{ Console.WriteLine("{0} C#2.0的委托的输出 匿名委托 {1}", i2, msg2); };

TestDelegate3 t3 = (msg3, i3) =>
{ Console.WriteLine("{0} C#3.0的委托输出 Lambdab表达式 {1}", i3, msg3); };

t1(msg,i++);
t2(msg,i++);
t3(msg,i++);
}
static void M3(string msg, int i)

{
Console.WriteLine("{0} C#1.0的委托的输出 {1}", i, msg);
}
#endregion
}
}
