using System;
using System.Collections.Generic;
using System.Text;
//事件允许一个对象将方式的事件通知其他对象,将发生的事件通知其他的对象称为发行者,同时对象也可以订阅事件,该对象
//称为订阅者
namespace interfaceDemo
{
//事件处理分为四步:
//1、定义事件
//2、使用委托定义事件
//3、订阅事件
//4、引发事件
//语法:[访问修饰符] event 委托名 事件名
class EventTest
{
public delegate void MathOp(int i, int j);//定义委托
public event MathOp eventMath;//事件定义
static void Main(string[] args)
{
EventTest et = new EventTest();//对象实例化
et.eventMath += new MathOp(Add);//订阅事件,实际上是添加一个指向方法的委托,当事件引发时将通过委托调用此方法,一个时间有多个订阅者,即通过委托可以将多个方法添加到某个事件中
Console.WriteLine("请输入两个正数:");
int m = int.Parse(Console.ReadLine());
int n = int.Parse(Console.ReadLine());
if (m > 0 & n > 0)//满足一定条件,引发事件
{
et.eventMath(m, n);
}
Console.ReadLine();
}
public static void Add(int i, int j)
{
Console.WriteLine("{0}+{1}={2}", i, j, i + j);
}
}
}