欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

简单介绍c#表达式树Expression简单类型比较demo的示例代码

程序员文章站 2022-04-06 14:48:11
...
下面小编就为大家带来一篇浅谈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的示例代码的详细内容,更多请关注其它相关文章!

相关标签: Expression,c#,demo