如何通过“名称”调用方法?

发布于 2024-11-06 16:46:10 字数 441 浏览 1 评论 0原文

如果我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

゛清羽墨安 2024-11-13 16:46:10

如果具体方法名称仅在运行时已知,则无法使用动态,需要使用如下内容:

t.GetMethod("Method1").Invoke(o, null);

这里假设 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:

t.GetMethod("Method1").Invoke(o, null);

This assumes, that Method1 has no parameters. If it does, you need to use one of the overloads of GetMethod and pass the parameters as the second parameter to Invoke.

一杯敬自由 2024-11-13 16:46:10

您可以使用:

// Use BindingFlags for non-public methods etc
MethodInfo method = t.GetMethod("Method1");

// null means "no arguments". You can pass an object[] with arguments.
method.Invoke(o, null);

请参阅 MethodBase.Invoke docs了解更多信息 - 例如传递参数。

如果您使用 C# 4 并且在编译时知道方法名称,那么 Stephen 使用 dynamic 的方法可能会更快(而且更容易阅读)。

(当然,如果可能的话,最好让所涉及的类型实现一个众所周知的接口。)

You would use:

// Use BindingFlags for non-public methods etc
MethodInfo method = t.GetMethod("Method1");

// null means "no arguments". You can pass an object[] with arguments.
method.Invoke(o, null);

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.)

奈何桥上唱咆哮 2024-11-13 16:46:10

最简单的方法:

dynamic myObject = o;
myObject.Method1();

The easiest way:

dynamic myObject = o;
myObject.Method1();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文