一。委托:
1.定义委托 public delegate void MyDelegate(string msg);
2.定义函数 这里委托相当于一个函数指针
public static void Func(string msg)
{
Console.WriteLine(msg);
}
3.创建实例并调用
MyDelegate md = new MyDelegate(Func);
md("fuck");
完整代码(不包括using部分)
namespace EventAndDelegate
{
public delegate void MyDelegate(string msg);
class Program
{
static void Main(string[] args)
{
MyDelegate md = new MyDelegate(Func);
md("fuck");
Console.ReadKey();
}
public static void Func(string msg)
{
Console.WriteLine(msg);
}
}
}
二。事件
1.定义事件 Timer myTimer = new Timer(100);
2.添加函数到事件队列(注意添加的函数参数固定)
myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
static void WriteChar(object source, ElapsedEventArgs e)
{
Console.Write(DisplayString[counter++ % DisplayString.Length]);
}
3.开始事件 myTimer.Start();
三。编写自己的事件,与委托结合
1.定义事件类
namespace EventAndDelegate
{
public delegate void DelHandler(string msg);
class MyEvent
{
Timer myTimer;
public event DelHandler MyEv;
public MyEvent()
{
myTimer = new Timer(100);
myTimer.Elapsed += EventFunc;
}
public void Connect()
{
myTimer.Start();
}
public void DisConnect()
{
myTimer.Stop();
}
private void EventFunc(object sender, EventArgs e)
{
Console.WriteLine("Here comes message!");
Random rad = new Random();
if (rad.Next(5) == 0 && MyEv != null)
{
MyEv("Fuck,finally turns to me !");
}
}
}
}
2.定义事件执行函数类
namespace EventAndDelegate
{
class MyEventFunc
{
public void Fucn(string msg)
{
Console.WriteLine("I say:" + msg);
}
}
}
3.主类中实现
namespace EventAndDelegate
{
public delegate void MyDelegate(string msg);
class Program
{
static void Main(string[] args)
{
MyEvent me = new MyEvent();
MyEventFunc mef = new MyEventFunc();
me.MyEv += new DelHandler(mef.Fucn);
me.Connect();
Console.ReadKey();
}
}
}