淺談c#表達式樹Expression簡單類型比較demo。本站提示廣大學習愛好者:(淺談c#表達式樹Expression簡單類型比較demo)文章只能為提供參考,不一定能成為您想要的結果。以下是淺談c#表達式樹Expression簡單類型比較demo正文
實例如下:
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#表達式樹Expression簡單類型比較demo就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。