代码之家  ›  专栏  ›  技术社区  ›  Dr. Rajesh Rolen

在system.reflection的invoke方法中将函数作为参数传递

  •  0
  • Dr. Rajesh Rolen  · 技术社区  · 14 年前

    我有一个包含函数层次结构的变量,如:

    string str= "fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()))" 
    

    //这个层次结构是作为数据库中的字符串来的

    我已经导入了System.reflection并使用invoke方法来调用它,但是只有在只有一个函数的情况下它才能工作 fun1 .

    在上面的函数层次结构中,它将完整的表达式作为一个函数名。

    我使用下面的代码调用我的函数层次结构:

    public static string InvokeStringMethod(string typeName, string methodName)
    {
    // Get the Type for the class
    Type calledType = Type.GetType(typeName);
    
    // Invoke the method itself. The string returned by the method winds up in s
    String s = (String)calledType.InvokeMember(
                    methodName,
                    BindingFlags.InvokeMethod | BindingFlags.Public | 
                        BindingFlags.Static,
                    null,
                    null,
                    null);
    
    // Return the string that was returned by the called method.
    return s;
    }  
    

    参考: http://www.codeproject.com/KB/cs/CallMethodNameInString.aspx

    请告诉我该怎么做?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Ondrej Tucny    14 年前

    问题是线路

    string str= fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));
    

    没有 表示一个表达式,或您所称的“函数层次结构”。相反,它执行赋值的右边 变成一个字符串值。

    你可能要找的是:

    Func<string> f = () => fun1(fun2(),fun3(fun4(fun5(34,33,'aa'),'value',fun6()));
    …
    string result = f();
    

    在这里,f是一个委托,您可以将lambda表达式(匿名方法)赋给它,稍后可以通过调用委托来执行 f