c# - Is there a way to register events in bulk? -
i have number of mother classes, each of these classes have different number of children objects of same type. , mother class need register event of these children objects.
wondering if there's way registration automatically?
something like: go through properties inside mother class, find properties of children type, , register event.
you can use reflections subscribe events.
define child class:
class child { public child() { } // define event public event eventhandler didsomethingnaughty; // proeprty used trigger event public bool isnaughty { { return this.isnaughty; } set { this.isnaughty = value; if (this.isnaughty) { if (this.didsomethingnaughty != null) { this.didsomethingnaughty(this, new eventargs()); } } } } // private data member property private bool isnaughty = false; }
define mother class:
class mother { public mother() { this.subscribetochildevent(); } // properties public child child1 { { return this.child1; } set { this.child1 = value; } } public child child2 { { return this.child1; } set { this.child2 = value; } } public child child3 { { return this.child3; } set { this.child3 = value; } } public child child4 { { return this.child4; } set { this.child4 = value; } } // private data members properties private child child1 = new child(); private child child2 = new child(); private child child3 = new child(); private child child4 = new child(); // uses reflection properties find of type child // , subscribe didsomethingnaughty event 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) 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 naughty"); // reset flag next time childe //naughty event raise child.isnaughty = false; } }
then initialize mother object , subscript events:
mother m = new mother();
then set isnaughty property of child1 true:
m.child1.isnaughty = true;
you should message box:
resources:
Comments
Post a Comment