傳統上,物件裡以+=來使用事件,不使用時用-=,
但有些情況必須頻繁的 += 與 -= ,若判斷很多就會加深複雜度,
如果物件裡的某個屬性可以做為判斷,就可以只用+=,再由類別取出物件的屬性來判斷是否執行事件處理的方法。
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void buttonClickEventHandle();
public event buttonClickEventHandle buttonClick;
MyClass fa,fb;
private void Form1_Load(object sender, EventArgs eee)
{
fa = new MyClass(this, "fa");
fb = new MyClass(this, "fb");
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
fa.Active = checkBox1.Checked;
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
fb.Active = checkBox2.Checked;
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Delegate d in buttonClick.GetInvocationList())
{
MyClass m = (MyClass)d.Target;
if (m.Active)
d.Method.Invoke(m, null);
}
}
internal class MyClass
{
internal Form1 form1;
internal string Name { set; get; }
internal bool Active { set; get; }
internal MyClass(Form1 form1, string name)
{
this.form1 = form1;
this.Name = name;
form1.buttonClick += form1_buttonClick;
}
void form1_buttonClick()
{
MessageBox.Show(this.Name);
}
}
}
}