如何通过“名称”调用方法?
如果我有一个Object
并且它是Type
,那么按名称调用某些方法(例如“Method1”)的方法是什么?
我想做这样的事情:
Object o;
Type t;
// At this point I know, that 'o' actually has
// 't' as it's type.
// And I know that 't' definitely has a public method 'Method1'.
// So, I want to do something like:
Reflection.CallMethodByName(o, "Method1");
这可能吗?我确实意识到这会很慢,很不方便,但不幸的是我没有其他方法来实现就我而言。
What would be the way to call some method by name, like "Method1", if I've got an Object
and it's Type
?
I want to do something like this:
Object o;
Type t;
// At this point I know, that 'o' actually has
// 't' as it's type.
// And I know that 't' definitely has a public method 'Method1'.
// So, I want to do something like:
Reflection.CallMethodByName(o, "Method1");
Is this somehow possible? I do realize that this would be slow, it's inconvenient, but unfortunately I've got no other ways to implement this in my case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果具体方法名称仅在运行时已知,则无法使用动态,需要使用如下内容:
这里假设
Method1
没有参数。如果是这样,您需要使用GetMethod
的重载之一,并将参数作为第二个参数传递给Invoke
。If the concrete method name is only known at runtime, you can't use dynamic and need to use something like this:
This assumes, that
Method1
has no parameters. If it does, you need to use one of the overloads ofGetMethod
and pass the parameters as the second parameter toInvoke
.您可以使用:
请参阅
MethodBase.Invoke docs
了解更多信息 - 例如传递参数。
如果您使用 C# 4 并且在编译时知道方法名称,那么 Stephen 使用
dynamic
的方法可能会更快(而且更容易阅读)。(当然,如果可能的话,最好让所涉及的类型实现一个众所周知的接口。)
You would use:
See
MethodBase.Invoke
docs for more information - e.g. passing arguments.Stephen's approach using
dynamic
will probably be faster (and definitely easier to read) if you're using C# 4 and you know the method name at compile time.(If at all possible, it would be nicer to make the type involved implement a well-known interface instead, of course.)
最简单的方法:
The easiest way: