如何迭代C#类查找特定类型的所有实例,然后在每个实例上调用一个方法 [英] How to iterate a C# class look for all instances of a specific type, then calling a method on each instance

查看:434
本文介绍了如何迭代C#类查找特定类型的所有实例,然后在每个实例上调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以(通过反射?)迭代对象的所有字段,并在每个字段上调用方法.

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

我有一个这样的班级:

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()
    }    
}     

可以做到吗?我已经能够获得Control类的所有元数据,但这仅与类型有关,而与特定实例无关.

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.

我知道这似乎很奇怪,但是我有我的理由.我正在使用Unity 3D,每个控件实际上都是由编辑器实例化的GUI控件.

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.

感谢您的帮助.

推荐答案

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();
            }
        }
    }
}

注意:这将过滤掉不是控件的类中的字段.此外,对于任何符合以下条件的字段类型, IsAssignableFrom 将返回true假定您也希望处理这些字段,则从Control继承.

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.

这篇关于如何迭代C#类查找特定类型的所有实例,然后在每个实例上调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆