The following small series for everyone to bring a brief introduction to C # expression tree expressions Simple Type comparison demo. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
Examples are as follows:
Using system;using system.linq.expressions;class dynamicpredicate{public static expression<func<t, T, bool>& Gt Generate<t> (String op) {parameterexpression x = Expression.parameter (typeof (T), "X"); ParameterExpression y = Expression.parameter (typeof (T), "Y"); Return expression.lambda<func<t, T, bool>> (op. Equals (">"))? Expression.greaterthan (x, y): (Op. Equals ("<"))? Expression.lessthan (x, y): (Op. Equals (">="))? Expression.greaterthanorequal (x, y): (Op. Equals ("<="))? Expression.lessthanorequal (x, y): (Op. Equals ("! ="))? Expression.notequal (x, y): expression.equal (x, y), x, y); }}static void Main () {string op = ">="; var integerpredicate = dynamicpredicate.generate<int> (OP). Compile (); var floatpredicate = dynamicpredicate.generate<float> (OP). Compile (); int IA = n, IB = 4; Console.WriteLine ("{0} {1} {2}: {3}", IA, OP, IB, Integerpredicate (IA, IB)); float FA = 867.0f, FB = 867.0f; Console.WriteLine ("{0} {1} {2}: {3}", FA, OP, FB, Floatpredicate (FA, FB)); Console.WriteLine ("{0} {1} {2}: {3}", FA, ">", FB, Dynamicpredicate.generate<float> (">"). Compile () (FA, FB)); Console.ReadLine (); }