0
我有許多母類,每個類都有不同數量的相同類型的子對象。母親班需要向所有這些孩子對象註冊一個事件。有沒有辦法可以批量註冊活動?
想知道是否有任何好方法自動進行註冊?
類似於:遍歷母類中的所有屬性,查找子類型的屬性以及註冊事件。
我有許多母類,每個類都有不同數量的相同類型的子對象。母親班需要向所有這些孩子對象註冊一個事件。有沒有辦法可以批量註冊活動?
想知道是否有任何好方法自動進行註冊?
類似於:遍歷母類中的所有屬性,查找子類型的屬性以及註冊事件。
您可以使用反射來訂閱事件。
定義子類:
class Child {
public Child() { }
// Define event
public event EventHandler DidSomethingNaughty;
// Proeprty used to trigger event
public bool IsNaughty {
get { return this.isNaughty; }
set {
this.isNaughty = value;
if (this.IsNaughty) {
if (this.DidSomethingNaughty != null) {
this.DidSomethingNaughty(this, new EventArgs());
}
}
}
}
// Private data member for property
private bool isNaughty = false;
}
定義媽媽級:
class Mother {
public Mother() {
this.subscribeToChildEvent();
}
// Properties
public Child Child1 {
get { return this.child1; }
set { this.child1 = value; }
}
public Child Child2 {
get { return this.child1; }
set { this.child2 = value; }
}
public Child Child3 {
get { return this.child3; }
set { this.child3 = value; }
}
public Child Child4 {
get { return this.child4; }
set { this.child4 = value; }
}
// Private data members for the properties
private Child child1 = new Child();
private Child child2 = new Child();
private Child child3 = new Child();
private Child child4 = new Child();
// This uses reflection to get the properties find those of type child
// and subscribe to the DidSomethingNaughty event for each
private void subscribeToChildEvent() {
System.Reflection.PropertyInfo[] properties =
typeof(Mother).GetProperties();
foreach (System.Reflection.PropertyInfo pi in properties) {
if (pi.ToString().StartsWith("Child")) {
Child child = pi.GetValue(this, null) as Child;
child.DidSomethingNaughty +=
new EventHandler(child_DidSomethingNaughty);
}
}
}
private void child_DidSomethingNaughty(object sender, EventArgs e){
Child child = (Child)sender;
if (child.IsNaughty) {
this.discipline(child);
}
}
private void discipline(Child child) {
MessageBox.Show("Someone was naughty");
// reset the flag so the next time the childe is
//naughty the event will raise
child.IsNaughty = false;
}
}
然後初始化一個母親的對象,它會下標事件:
Mother m = new Mother();
然後設置IsNaughty Child1屬性爲true:
m.Child1.IsNaughty = true;
你應該得到一個消息框:
資源:
「註冊事件給所有這些孩子的對象」。從這個聲明中不清楚這種關係是哪一方(誰是調度員,誰是接收者)。爲什麼不張貼一些代碼給我們看? – spender
是不是委託的多播性質假設這樣做。您向發佈商訂閱了很多方法?所以,如果母親班與這個委託或事件共享,所有的孩子都可以訂閱它。也許我沒有正確地理解它。 –
使其更清楚。目前還不清楚 –