浅谈c#表达式树Expression简单类型比较demo
时间:2020-12-18 02:21:37|栏目:.NET代码|点击: 次
实例如下:
using System; using System.Linq.Expressions; class DynamicPredicate { public static Expression<Func<T, T, bool>> 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 = 12, 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(); }
上一篇:c# StringBuilder.Replace 方法 (Char, Char, Int32, Int32)
栏 目:.NET代码
下一篇:C#实现的文件压缩和解压缩类
本文标题:浅谈c#表达式树Expression简单类型比较demo
本文地址:http://www.codeinn.net/misctech/34152.html