2013-07-23 42 views
0

我有许多母类,每个类都有不同数量的相同类型的子对象。母亲班需要向所有这些孩子对象注册一个事件。有没有办法可以批量注册活动?

想知道是否有任何好方法自动进行注册?

类似于:遍历母类中的所有属性,查找子类型的属性以及注册事件。

+0

“注册事件给所有这些孩子的对象”。从这个声明中不清楚这种关系是哪一方(谁是调度员,谁是接收者)。为什么不张贴一些代码给我们看? – spender

+0

是不是委托的多播性质假设这样做。您向发布商订阅了很多方法?所以,如果母亲班与这个委托或事件共享,所有的孩子都可以订阅它。也许我没有正确地理解它。 –

+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 m = new Mother(); 

然后设置IsNaughty Child1属性为true:

m.Child1.IsNaughty = true; 

你应该得到一个消息框:

You should get a message box:

资源:

https://stackoverflow.com/a/737156/1967692

https://stackoverflow.com/a/3179869/1967692

相关问题