視訊加載中...
一、事件的本質:
事件的就是對委托的進一步包裝,見視訊詳解;
二、事件
2.1在委托類型前面添加event就可以定義事件
2.2事件必須使用+=或者-=,不能直接=指派
2.3事件移除不能使用null,隻能使用-=方式
三、事件參與者
3.1發送者(sender):也就是用來激發事件,通知所有的接受者接收消息。
3.2接受者(Receiver):就是事件的處理者,在事件發送者觸發事件後,自動執行的代碼。
四、事件和委托對比
4.1事件無法在“外面”指派。比如“對象.事件=null",會出現編譯錯誤,而委托可以。
好處:避免使用者對事件直接操作,比如Click事件,如果允許Click=null,會把底層代碼清除。事件就可以起到保護作用。而委托相對”太開放“。
事件:把委托用不到的”功能和用法“去掉。
4.2、event對象沒有invoke()方法。
五、委托和事件的選擇
5.1正常解決問題,使用事件和委托沒有什麼本質差別,但建議用委托。
5.2如果我們做控件二次開發,擴充控件的事件時,必須要事件event。
六、代碼部分
6.1主窗體全部代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
//[1]建立委托
public delegate void ReceiveDelegate(string data);
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
//把子窗體對象放到容器中
private List<Form> formlist = new List<Form>();
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 4; i++)
{
FrmChild frm = new FrmChild(i);
frm.Show();
//【4】關聯委托變量 old
// frm.ReceiveDelegate = ReceiveMsg;
//【4】關聯委托變量 new
frm.ReceiveDelegate += ReceiveMsg;
//新增的,将窗體對象添加到集合,為了移除事件能通路到
formlist.Add(frm);
}
}
//[2]接收者
private void ReceiveMsg(string data)
{
this.textBox1.Text += data+"\r\n";
}
private void button2_Click(object sender, EventArgs e)
{
//之前新增窗體的是局部變量,這個地方是通路不到的,是以要周遊集合
foreach (FrmChild item in formlist)
{
//item.ReceiveDelegate = null;
item.ReceiveDelegate -= ReceiveMsg;//隻能通過這種方式移除事件
}
}
}
}
6.2子窗體代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class FrmChild : Form
{
public FrmChild(int num)
{
InitializeComponent();
this.Text += #34;[{num}]";
}
//[3]建立委托變量 - old
//public ReceiveDelegate ReceiveDelegate { get; set; }
//
//[3]建立委托變量 - new
public event ReceiveDelegate ReceiveDelegate;
private void button1_Click(object sender, EventArgs e)
{
//【5】激發事件 -
ReceiveDelegate(textBox1.Text);
}
}
}