Computing an Expression Tree with Many Parameters

I am trying to use the Expression tree and Expression Lamdba objects in .Net 3.5 to allow me to dynamically evaluate the logical expression entered by the user.

So far, the user can create an expression tree consisting of BinarayExpressionsthat the values โ€‹โ€‹AND and OR are expressed as ParameterExpressions. Then I planned to create LambdaExpressionbased on this tree so that I could compile this expression into a delegate, which I could then call. The problem I am facing is that I donโ€™t know how many input parameters the user will need when I come to compile the expression into a delegate. I do not know the method, what the signature of the method should be like before execution.

So far I have come up with two possible solutions.

  • Create a whole group of delegates like Func<bool, bool, bool...>, which can take as many parameters as it seems to me, the user may need. This doesn't seem like the most elegant solution, but I think it will work until someone wants to use another parameter that I served.
  • Pass an array of values โ€‹โ€‹and somehow assign them to my parameters using an array indexer. I thought about it, but I canโ€™t understand how it works.

NB: it must be fast so that it is not boxing or something like that.

+3
source share
1 answer

, ( Finguistics, ). Expression.ArrayIndex:

    var arr = Expression.Parameter(typeof(int[]), "arr");
    var body = Expression.ArrayIndex(arr, Expression.Constant(1));
    var expr = Expression.Lambda<Func<int[], int>>(body, arr);
    var func = expr.Compile();

    int[] vals = { 7, 8, 9 };
    int i = func(vals);

, (Func<int[],int> , . Invoke , DynamicInvoke.

- ; , .

+3

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


All Articles