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

浅谈c#表达式树Expression简单类型比较demo

程序员文章站 2023-11-09 18:37:28
实例如下: using system; using system.linq.expressions; class dynamicpredicate {...

实例如下:

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就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。