如何迭代 C# 类查找特定类型的所有实例,然后在每个实例上调用方法
是否可以(通过反射?)迭代对象的所有字段,并在每个字段上调用一个方法。
我有一个像这样的课程:
public class Overlay
{
public Control control1;
public Control control2;
}
我想要一个像这样的方法:
public void DrawAll()
{
Controls[] controls = "All instances of Control"
foreach (Control control in Controls)
{
control.Draw()
}
}
这可以完成吗?我已经能够获取 Control 类的所有元数据,但这仅与类型相关,而不与特定实例相关。
我知道这看起来很奇怪,但我有我的理由。我使用的是 Unity 3D,每个控件实际上都是由编辑器实例化的 GUI 控件。
感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:这将过滤掉类中非控件的字段。此外,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.
请注意,如果您的对象也没有
Control
字段,则需要通过GetValue()
添加额外的返回值类型检查。Note, that you need to add additional check of type of returned value by
GetValue()
if your object has also notControl
fields.