Implementation Not in .net 4 Expression Trees

Is it possible to implement a! (not) using expression trees. I am interested in creating a C # eval class that will parse and evaluate logical expressions that contain true, false, ||, && as well !. I know that && and || are currently supported by .NET 4 expression trees, but I was wondering if their way of implementing sumat like! (x && y) || z where z = false, y = true and z = false.

I am currently using a standard tokenizer, parser, standard stack based evaluator to evaluate these types of expressions, but happly dump it if a suitable expression tree could be created and executed on the fly.

+4
source share
3 answers

Usually I find it worthwhile to code a lambda expression that does what I want, and then see what the C # compiler does with it.

So this code:

Expression<Func<bool,bool>> func = x => !x; 

Compiled to:

 ParameterExpression expression2; Expression<Func<bool, bool>> expression = Expression.Lambda<Func<bool, bool>>(Expression.Not( expression2 = Expression.Parameter(typeof(bool), "x")), new ParameterExpression[] { expression2 }); 

(Apologies for formatting - it's hard to figure out what to do about it.)

This is decompiled with Reflector, but with its โ€œoptimizationโ€ installed on .NET 2.0, to avoid using lambda syntax.

Once you pass the trash, you will see it with Expression.Not . && uses Expression.AndAlso and || uses Expression.OrElse .

+9
source

It already exists in System.Linq.Expressions . See UnaryExpression . If there is something in the expressions that you donโ€™t like, I would suggest using them. There are also ways to create abstract syntax trees from source code, in particular in Microsoft.Scripting.Ast (found in DLR: Microsoft.Scripting).

+2
source

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


All Articles