C #, create (method?) Expression and call it

I am completely unfamiliar with the C # expression. I have some class, something like this

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

    public string Return(Expression exp)
    {
        LambdaExpression lambda = Expression.Lambda(exp);
        return lambda.Compile();
    }
}

Now I would like to call this Return method with some parameter something (pseudo) as follows:

      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);

Thanks for the help / answer.

Matt

+3
source share
2 answers

It would be better to provide a signature expas early as possible - for example,Expression<Func<string>>

public string Return(Expression<Func<string>> expression)
{
    return expression.Compile()();
}

through:

SimpleClass sc = new SimpleClass();
string result = sc.Return(() => sc.ReturnString("hello world"));
Console.WriteLine(result);

or

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);

Of course, using delegates ( Func<string>) can also work in many scenarios.

+6
source

- , . , delegate.

+3

Source: https://habr.com/ru/post/1715897/


All Articles