1、创建控制台程序
2、定义业务类和回调时传递的参数类型,如下:
class Work
{
public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);
public ValueChangedEventHandler ValueChanged;
public void DoWork()
{
if (ValueChanged!=null)
{
ValueChanged(this, new ValueChangedEventArgs(DateTime.Now.Second));
}
}
}
public class ValueChangedEventArgs : EventArgs
{
public ValueChangedEventArgs(int value)
{
this.Value = value;
}
public int Value;
}
3、在Main中使用业务类,并定义回调处理逻辑,如下:
class Program
{
static void Main(string[] args)
{
Work work = new Work();
//方式一
work.ValueChanged += (o, e) =>{
Console.WriteLine("方式一:" + Convert.ToString(e.Value));
};
//方式二
work.ValueChanged += ChangedHandler;
work.DoWork();
System.Threading.Thread.Sleep(3 * 1000);
work.DoWork();
Console.Read();
}
private static void ChangedHandler(object sender, ValueChangedEventArgs e)
{
Console.WriteLine("方式二:" + Convert.ToString(e.Value));
}
}
4、运行,结果如下:
方式一:45
方式二:45
方式一:48
方式二:48