Implement Not in expression trees, .net 4

谁都会走 提交于 2019-12-05 16:23:37

I usually find that it's worth coding a lambda expression which does what I want, and then seeing what the C# compiler does with it.

So this code:

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

Is compiled into:

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 the formatting - it's hard to know what to do with that.)

That's decompiled with Reflector, but with its "optimization" set at .NET 2.0 to avoid it using lambda syntax.

Once you've got past the junk, you'll see it's using Expression.Not. && uses Expression.AndAlso, and || uses Expression.OrElse.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!