c# - How to find all objects that implement a interface and invoke a method -


i have usercontrol have few child usercontrol's , usercontrol's have child usercontrol's.

consider this:

mainusercontrol   tabcontrol     tabitem       usercontrol         usercontrol           usercontrol : isomeinterface     tabitem       usercontrol         usercontrol           usercontrol : isomeinterface     tabitem       usercontrol         usercontrol           usercontrol : isomeinterface     tabitem       usercontrol         usercontrol           usercontrol : isomeinterface 

this have far, finds no isomeinterface:

propertyinfo[] properties = mainusercontrol.gettype().getproperties(); foreach (propertyinfo property in properties) {     if (typeof(isomeinterface).isassignablefrom(property.propertytype))     {         property.gettype().invokemember("somemethod", bindingflags.invokemethod, null, null, null);     } } 

is possible find child usercontrol's mainusercontrol implement isomeinterface via reflection , call method(void somemethod()) on interface?

you need recursively iterate through subcontrols within mainusercontrol.

here's helper method can use:

/// <summary> /// recursively lists controls under specified parent control. /// child controls listed before parents. /// </summary> /// <param name="parent">the control child controls returned</param> /// <returns>returns sequence of controls on control or of children.</returns>  public static ienumerable<control> allcontrols(control parent) {     if (parent == null)     {         throw new argumentnullexception("parent");     }      foreach (control control in parent.controls)     {         foreach (control child in allcontrols(control))         {             yield return child;         }          yield return control;     } } 

then:

foreach (var control in allcontrols(mainusercontrol)) {     propertyinfo[] properties = control.gettype().getproperties();     ... loop iterating on properties 

or (much better if work you, since it's lot simpler):

foreach (var control in allcontrols(mainusercontrol)) {     var someinterface = control isomeinterface;      if (someinterface != null)     {         someinterface.somemethod();     } } 

or, using linq (need using system.linq this):

foreach (var control in allcontrols(mainusercontrol).oftype<isomeinterface>())     control.somemethod(); 

which seems best of all. :)


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -