As an iteration of a class, C # looks for all instances of a particular type, and then a method call for each instance

Is it possible (through reflection?) To sort through all the fields of the object that calls the method on each of them.

I have a class like:

public class Overlay { public Control control1; public Control control2; } 

I need a method that looks something like this:

 public void DrawAll() { Controls[] controls = "All instances of Control" foreach (Control control in Controls) { control.Draw() } } 

Can this be done? I managed to get all the metadata in the Control class, but this only applies to the type and not to the specific instance.

I know this seems strange, but I have reasons. I use Unity 3D, and each control is actually a GUI control created by an editor.

Thanks for any help.

+4
source share
3 answers
 public class Program { static void Main(string[] args) { Overlay overlay = new Overlay(); foreach (FieldInfo field in overlay.GetType().GetFields()) { if(typeof(Control).IsAssignableFrom(field.FieldType)) { Control c = field.GetValue(overlay) as Control; if(c != null) c.Draw(); } } } } 

Note. This will filter out fields in the class that are not controls. In addition, IsAssignableFrom will return true for any field types that inherit from Control, provided that you want to process these fields.

+3
source
 var props = typeof(Overlay).GetProperties().OfType<Control>(); 
+2
source
 Overlay obj = new Overlay(); Type t = typeof(Overlay); FieldInfo[] fields = t.GetFields(); foreach (FieldInfo info in fields) { Control c = (Control)info.GetValue(obj); c.Draw(); } 

Note that you need to add an additional type check for the return value to GetValue() if your object also has Control fields.

+1
source

All Articles