思路
写两个类,一个类A的方法注册另一个类B的事件,当类B的事件触发(invoke)的时候,会调用A的方法.
测试委托的demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _9_测试委托
{
class DEvent
{
public delegate void dReceiver(object sender, string str);
public event dReceiver receive;
public void invokeEvent(object sender,string str)
{
receive.Invoke(sender, str);
}
}
class Program
{
public void BeCalled(object obj,string msg)
{
Console.WriteLine(msg);
}
public void useEvent()
{
DEvent de = new DEvent();
de.receive += new DEvent.dReceiver(this.BeCalled);
for (int i = 0; i < 10; i++)
{
de.invokeEvent(null, "呵呵" + i);
System.Threading.Thread.Sleep(1000);
}
}
static void Main(string[] args)
{
Program p = new Program();
p.useEvent();
}
}