Dar*_*der 5 .net c# web-services read-eval-print-loop
这是我想要做的,我知道它可能与perl,php,python和java,但我正在使用c#
我该怎么做:
public void amethod(string functionName)
{
AVeryLargeWebServiceWithLotsOfMethodsToCall.getFunctionName();
}
Run Code Online (Sandbox Code Playgroud)
我想将functionName传递给方法,我希望它如上所述执行.
怎么做到这一点?
我需要ANTLR或任何其他工具吗?
谢谢.
您可以通过Reflection按名称执行方法.您需要知道类型以及方法名称(可以是当前对象的类型,或不同对象上的方法,或静态类型).它看起来像你想要的东西:
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
}
Run Code Online (Sandbox Code Playgroud)
编辑以回应评论:
听起来你真的想从这个方法中得到一个结果.如果是这种情况,假设它仍然是服务上的静态方法(这是我的猜测,根据你写的内容),你可以这样做. MethodInfo.Invoke会直接将方法的返回值作为Object返回,因此,例如,如果您返回一个字符串,则可以执行以下操作:
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.
}
Run Code Online (Sandbox Code Playgroud)
在c#中执行一个字符串就好像它是代码一样,但它并不漂亮或简单.它也被认为是不良的做法和不安全(你可能也应该在动态语言中避免它).
相反,做这样的事情:
public void amethod(Action actionParam)
{
actionParam();
}
Run Code Online (Sandbox Code Playgroud)
现在,在您的情况下,您想要调用Web服务.因为最终归结为xml,你有几个选择: