这是我想做的,我知道可以使用 perl、php、python 和 java,但我正在使用 c#
我怎样才能做到以下几点:
public void amethod(string functionName)
{
AVeryLargeWebServiceWithLotsOfMethodsToCall.getFunctionName();
}
我想将 functionName 传递给方法,我希望它像上面那样执行。
如何做到这一点?
我需要 ANTLR 或任何其他工具吗?
谢谢。
最佳答案
您可以通过反射按名称执行方法。您需要知道类型以及方法名称(可以是当前对象的类型,或不同对象上的方法,或静态类型)。看起来你想要这样的东西:
public void amethod(string functionName)
{
Type type = typeof(AVeryLargeWebServiceWithLotsOfMethodsToCall);
MethodInfo method = type.GetMethod(functionName, BindingFlags.Public | BindingFlags.Static);
method.Invoke(null,null); // Static methods, with no parameters
}
编辑以回应评论:
听起来你真的想从这个方法中得到一个结果。如果是这种情况,鉴于它仍然是服务上的静态方法(这是我的猜测,考虑到你写的内容),你可以这样做。 MethodInfo.Invoke将直接将方法的返回值作为对象返回,因此,例如,如果您要返回一个字符串,您可以这样做:
public string amethod(string functionName)
{
Type type = typeof(AVeryLargeWebServiceWithLotsOfMethodsToCall);
MethodInfo method = type.GetMethod(functionName, BindingFlags.Public | BindingFlags.Static);
object result = method.Invoke(null,null); // Static methods, with no parameters
if (result == null)
return string.Empty;
return result.ToString();
// Could also be return (int)result;, if it was an integer (boxed to an object), etc.
}
关于c# 将字符串作为代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1511376/