Reflection.MethodInfo

编程入门 行业动态 更新时间:2024-10-26 06:36:01
本文介绍了Reflection.MethodInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过名称调用方法-在aspx代码隐藏类中作为字符串传入,如下所示:

I'm trying to invoke a method by name - passed in as a string in an aspx code-behind class, like this:

private void callMethod( string method ) { object classInstance = Activator.CreateInstance( this.GetType(), null ); MethodInfo methodInfo = GetType().GetMethod( method ); methodInfo.Invoke( classInstance, null ); }

但是该方法在继承的类中,并且此代码找不到该方法.有人可以帮我吗?

But the method is in an inherited class and this code can't find the method. Could someone please help me?

推荐答案

尝试将 BindingFlags 添加到您的 GetMethod()调用中.

Try adding BindingFlags to your GetMethod() call.

例如,假设您要使用的方法是公共的而不是静态的:

For instance, assuming the method you want is public and not static:

MethodInfo methodInfo = GetType().GetMethod( method, BindingFlags.Instance | BindingFlags.Public );

在这里您将找到有关 BindingFlags 及其可能值的更多信息:

Here you will find more information about BindingFlags and its possible values:

msdn.microsoft/zh-我们/library/system.reflection.bindingflags.aspx

这来自文档:

注意

您必须指定实例"或静态"以及公共"或非公共",否则将不返回任何成员.

You must specify Instance or Static along with Public or NonPublic or no members will be returned.

另一种方法是查询方法:

Another way is to query the methods:

MethodInfo methodInfo = GetType().GetMethods().FirstOrDefault(x => x.Name == method);

所有这一切都假设您找到的方法是无参数的.如果它们具有参数,那么,您需要将该信息添加到 GetMethod()或 GetMethods()方法中.这里是一些文档:

All this is assuming the methods you are finding are parameterless. If they have parameters, well, you'll need to add that information to the GetMethod() or GetMethods() method. Here is some documentation:

msdn.microsoft/zh-我们/library/system.type.getmethod.aspx

msdn.microsoft/zh-我们/library/system.type.getmethods.aspx

最后,在这种情况下创建页面类的新实例似乎有些奇怪.也许您实际上是想对页面的当前实例执行该方法,而不是执行一个新实例,在这种情况下,您的代码应更像:

Finally, it seems a little bit weird to create a new instance of the page class in that scenario. Maybe you actually want to execute the method to the current instance of the page instead a new one, in which case your code should look more like:

private void callMethod( string method ) { MethodInfo methodInfo = GetType().GetMethod( method ); methodInfo.Invoke( this, null ); }

希望有帮助!

更多推荐

Reflection.MethodInfo

本文发布于:2023-11-05 04:17:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559879.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Reflection   MethodInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!