1

A quick sample to understand my situation:

static Interpreter ParseInterpreter = new Interpreter();
...
var func = ParseInterpreter.Parse("ctx.SomeProp", new Parameter("ctx", typeof(???1)).Compile<Func<???2, object>>;
...
var token = JToken.Parse(s);
dynamic dToken = token;
var obj = func(dToken);

In other words, is there a way to pass some dynamic parameter to Parse method and then get a functor which accepts such parameters?

ProfyTroll
  • 281
  • 5
  • 18

1 Answers1

1

You can directly use the Lambda class returned by the Parse method, and not call the Compile function:

var interpreter = new Interpreter()
string expression = "ctx.SomeProp";
Lambda parsedExpression = interpreter.Parse(expression, new Parameter("ctx", typeof(object)));
var token = JToken.Parse(s);
var result = parsedExpression.Invoke(token);

I have not tested exactly your code but for example I have a test like this that works correctly:

dynamic dyn = new ExpandoObject();
dyn.Foo = "bar";
var interpreter = new Interpreter()
    .SetVariable("dyn", (object)dyn);
Assert.AreEqual(dyn.Foo, interpreter.Eval("dyn.Foo"));

Consider that this only works on .NET 4.x, on .NET Standard/Core dynamics are not supported.

Davide Icardi
  • 11,919
  • 8
  • 56
  • 77
  • Thanks for rapid response! I'd prefer to compile expression due to performance demands. The idea behind all of this is json transformation - JUST library disappointed me greatly under heavy load (and have terrible syntax in transformation rules alongside). Anyway I'll give a try to Lambda and give feedback ASAP. – ProfyTroll Jun 29 '18 at 21:18
  • @ProfyTroll Internally the expression is always compiled, the difference is that in this case I compile to a Delegate. But performance should be similar. Sometime ago I have done a similar experiment: https://github.com/deltatre-webplu/DynamicExpresso.Template – Davide Icardi Jun 30 '18 at 07:50
  • Thanks to you, I managed to Compile expression and use JToken dynamically inside. Regarding Delegate vs Func - internally as I see it's Delegate.DynamicInvoke, which should be slower than compiled functor anyway. Though I must admit that I did not do any measurements and not sure how much slower it is, it might be relatively small difference. – ProfyTroll Jun 30 '18 at 18:26
  • UPD: Seems somebody did the experiment https://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke and I must say the difference is huge – ProfyTroll Jun 30 '18 at 18:31