C# 事件,委托与事件的区别

来源:互联网 发布:知乎 刘家昌告华纳 编辑:程序博客网 时间:2024/05/16 03:49

委托实例的调用可以在声明委托的类的内部和外部调用(不安全)。  

事件对象的调用只能在什么事件的类的内部调用(安全)。(事件和委托的使用代码几乎完全相同)

public event SendMsgDel SendMsgDelEvent;  //声明事件(SendMsgDel) 及其对象(SendMsgDelEvent)SendMsgDelEvent += SetMsgTextEvent1;  //将函数(SetMsgTextEvent)绑定到事件对象中。SendMsgDelEvent += SetMsgTextEvent2;  //将函数(SetMsgTextEvent)绑定到事件对象中。SendMsgDelEvent(DateTime.Now.ToString() + "   ---");  //调用事件 (事件中的所有函数都会执行);只能在声明事件的类的内部调用,比较安全。public void SetMsgTextEvent1(string str){    this.txtMessage.Text = " 事件:" + str;}public void SetMsgTextEvent2(string str){    this.txtMessage.Text = " 事件:" + str;}



原创粉丝点击