我正在尝试通过名称调用方法-在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
发布评论