我有多个母班,每个班级都有不同数量的同一类型的儿童对象。母班需要向所有这些子对象注册一个事件。
想知道是否有任何好方法可以自动进行注册?
类似于:浏览母类中的所有属性,查找子类型的属性,并注册事件。
答案 0 :(得分: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对象,它将下标到事件:
Mother m = new Mother();
然后将Child1的IsNaughty属性设置为true:
m.Child1.IsNaughty = true;
您应该收到一个消息框:
资源: