C#中执行字符串作为code字符串、code

2023-09-03 01:07:01 作者:你给的伤数不清

下面是我想做的事情,我知道这可能是用Perl,PHP,Python和Java,但我使用C#的工作

Here is what i want to do, and i know it is possible with perl, php, python and java, but i am working with c#

我怎么能做到以下几点:

how can i do the following:

public void amethod(string functionName)
{
    AVeryLargeWebServiceWithLotsOfMethodsToCall.getFunctionName();
}

我要的函数名传递给方法,我希望它是如上执行。

I want to pass the functionName to the method and I want it to be executed as above.

这可怎么办呢?

我是否需要ANTLR或任何其他工具,这一点?

Do i need ANTLR or any other tool for this?

感谢。

推荐答案

您可以按名称通过反射执行的方法。您需要知道的类型,以及该方法名(可以是当前对象的类型,或在不同的对象的方法,或形成的静止型)。它看起来像你想是这样的:

You can execute a method by name via Reflection. You need to know the type, as well as the method name (which can be the current object's type, or a method on a different object, or a static type). It looks like you want something like:

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 将直接返回该方法的返回值作为一个对象,所以,如果,例如,你正在返回一个字符串,你可以这样做:

It sounds like you actually want to get a result back from this method. If that's the case, given that it's still a static method on the service (which is my guess, given what you wrote), you can do this. MethodInfo.Invoke will return the method's return value as an Object directly, so, if, for example, you were returning a string, you could do:

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.
}