1.定义事件1
角色:
事件发布者:发布事件 (触发事件的对象)
事件订阅者:接受事件,相应处理(捕获事件并且对其处理)
定义事件:访问修饰符 event 委托类型 事件名
1.修饰符一般为公有public 对其它类可见
2.委托类型可以是自定义委托类型,或者预定义的EventHandler
int main()
{ friend f1 = new friend ();
friend f2 = new friend ();
bridge.myevent +=f1.thing;
bridge.myevent +=f2.thing; //订阅事件
bridge.myevent -=f2.thing; //移除事件
bridge.sendthing (); //发布事件.通过委托链调用委托链的方法 通过公有方法间接调用事件
} //事件不可以在类外面直接调用 bridge.myevent()将会报错!
class bridge
{ public delegate void mydele();
public static event mydele myevent;
public static void sendthing() { myevent(); } //公有方法
}
class friend
{ public void thing() { Console.WriteLine ("wo zhi dao le !"); }
}
1.定义事件2
原型:public delegate void EventHandler (object sender, EventArgs e);
可以使用系统提供的委托类型 EventHandler
public event EventHandler myevent; //bridge
public void sendthing(string time,string place)
{ EventArgs e = new EventArgs(time,place);
myevent (this,e); //this是谁发出的
}
public class Myeventargs :EventArgs //扩展EventArgs,可以传递参数
{
protected string time;
protected string place;
public Myeventargs(string time,string place)
{ this.time = time;
this.place = place;
}
}
public void thing(object sender,EventArgs e) //friend
{
Console.WriteLine ("{0}收到{1}的通知了,时间{2}地点{3} ",
name,((bridge)sender).name,((Myeventargs)e).time,((Myeventargs)e).place);
}
int main()
{
bridge b = new bridge ("xin", 22); //main
friend f1 = new friend ("a", 21);
b.myevent += f1.thing;
b.sendthing ("2017", "beijing");
}