How to iterate a C# class look for all instances of a specific type, then calling a method on each instance

佐手、 提交于 2019-12-10 18:12:12

问题


Is it possible (via reflection?) to iterate all fields of an object calling a method on each one.

I have a class like so:

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

I'd like a method that goes something like this:

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

Can this be done? I've been able to get all the metadata on the Control class but this relates only to the type not the specific instance.

I know this seems odd but I have my reasons. I'm using Unity 3D and each control is actually a GUI control instantiated by the editor.

Thanks for any help.


回答1:


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 aren't controls. Also, IsAssignableFrom will return true for any field types that inherit from Control, assuming you wish to handle these fields as well.




回答2:


var props = typeof(Overlay).GetProperties().OfType<Control>();



回答3:


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 additional check of type of returned value by GetValue() if your object has also not Control fields.



来源:https://stackoverflow.com/questions/6146640/how-to-iterate-a-c-sharp-class-look-for-all-instances-of-a-specific-type-then-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!