如何在不同类的另一个实例中循环访问一个类的每个离散实例并调用特定方法
我有一个类,它使用各种方法和其他类作为其成员。在其中一个方法中,它执行如下操作:
MyObject.member1.doStuff();
MyObject.member2.doStuff();
MyObject.member3.doStuff();
MyObject.member4.doStuff();
等等。
我想做这样的操作:
foreach Member in MyObject
{
foreach Method in Member
{
if (Method.Name == "doStuff")
{ Method.Invoke() }
}
}
每个成员都属于不同的类类型,它们唯一的共同点是它们都有一个名为 doStuff 的 void 方法()。我无法将所有方法合并到一个巨大的 doStuff() 方法中。
I have a class that uses a variety of methods and other classes as its members. In one of these methods, it does something like this:
MyObject.member1.doStuff();
MyObject.member2.doStuff();
MyObject.member3.doStuff();
MyObject.member4.doStuff();
etc.
I would like to do something like this instead:
foreach Member in MyObject
{
foreach Method in Member
{
if (Method.Name == "doStuff")
{ Method.Invoke() }
}
}
Each member is of a different class type, the only thing they have in common is they will all have a void method called doStuff(). I cannot combine all methods into one giant doStuff() method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你必须在这里使用接口:
you have to use interface here:
假设您正在谈论的成员是属性,您可以执行以下非常丑陋的代码:
但正如已经提到的,这似乎是您的体系结构的问题。
Assuming the members you are talking about are properties, you can do the following very ugly code:
But as has been mentioned, it seems like a problem with your architecture.
如果您必须使用反射来对此类属性进行方法调用,则意味着您的代码很可能设计不当。
如果您已经知道这些方法,则可以将它们放入
Action
数组中:If you have to use reflection for method calls on properties like that it means your code is most likely ill-designed.
If you know the methods already you can just put them into an
Action
array though: