1

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

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

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

4

1 回答 1

4

尝试添加BindingFlags到您的GetMethod()通话中。

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

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

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

http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

这是来自文档:

笔记

您必须指定 Instance 或 Static 以及 Public 或 NonPublic,否则将不返回任何成员。

另一种方法是查询方法:

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

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

http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx

http://msdn.microsoft.com/en-us/library/system.type.getmethods.aspx

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

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

希望能帮助到你!

于 2012-10-20T15:20:19.027 回答