下面小編就為大家帶來一篇淺談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的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!