C#,create(method?)表达式并调用它

3 c# expression

我是c#表达式的新手.我有类似的课

class SimpleClass
{
    private string ReturnString(string InputString)
    {
        return "result is: "+InputString;
    }

    public string Return(Expression exp)
    {
        LambdaExpression lambda = Expression.Lambda(exp);
        return lambda.Compile();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我想调用这个方法返回一些参数(伪)像这样:

      SimpleClass sc = new SimpleClass();
      Expression expression = Expression.MethodCall(//how to create expression to call SimpleClass.ReturnString with some parameter?);
     string result = sc.Return(expression);
    Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助/回答.

马特

Mar*_*ell 6

最好exp尽早执行签名 - 即作为Expression<Func<string>>

public string Return(Expression<Func<string>> expression)
{
    return expression.Compile()();
}
Run Code Online (Sandbox Code Playgroud)

与任何一个:

SimpleClass sc = new SimpleClass();
string result = sc.Return(() => sc.ReturnString("hello world"));
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)

要么:

SimpleClass sc = new SimpleClass();
Expression expression = Expression.Call(
    Expression.Constant(sc),           // target-object
    "ReturnString",                    // method-name
    null,                              // generic type-argments
    Expression.Constant("hello world") // method-arguments
);
var lambda = Expression.Lambda<Func<string>>(expression);
string result = sc.Return(lambda);
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)

当然,委托使用(Func<string>)在许多情况下也可以正常工作.