开发者

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

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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜