轻量级表达式引擎 flee

 

最近发现一个非常好用的表达式引擎类库。官方站点
 
官方的介绍:
A .NET library that allows you to parse, compile, and evaluate expressions.  Its main distinguishing feature is that it uses a custom compiler to convert expressions to IL and then emits them to a dynamic method at runtime.  This ensures that expression evaluation is fast and efficient.
 
用来分析、编译、执行表达式的NET类库。他的主要实现方法是将表达式在运行时编译成IL的EMITS。然后生成为动态方法。所以执行速度和灵活性大大超越一般基于字符解析的表达式引擎
 
应用场景
•1.报表
•2.工作流配置
•3.自定义控件
•4.配置系统的后台
 
可以导入类库、导入变量、构造表达式上下文
例如:
代码
 
      
1 // 创建表达式环境
2   ExpressionContext context = new ExpressionContext();
3 // 引入Math类库到环境中
4 context.Imports.AddType( typeof (System.Math));
5 // 添加一个变量
6 context.Variables[ " a " ] = 100 ;
7 // 编译表达式
8 IDynamicExpression eDynamic = context.CompileDynamic( " sqrt(a) + pi " );
9 // 执行表达式
10 double result = ( double )eDynamic.Evaluate();
11
12 IGenericExpression < double > eGeneric = context.CompileGeneric < double > ( " sqrt(a) + pi " );
13 result = eGeneric.Evaluate();
14
15 context.Variables[ " a " ] = 144 ;
16 result = eGeneric.Evaluate();

 

因为他本身就是注入到NET IL中去的,所以可以直接调用成员函数,例如:

直接调用公开成员
 
      
1 ExpressionContext context = new ExpressionContext();
2 context.Variables[ " s " ] = " 你好! "
3 IDynamicExpression e = context.CompileDynamic( " s.length + s.Remove(0, 1).length " );
4 int length = ( int )e.Evaluate();

 

 

其他示例
 
      
1 // 引入自定义类,可以调用静态方法
2 ExpressionContext context1 = new ExpressionContext();
3 context1.Imports.AddType( typeof (CustomFunctions));
4 context1.Variables.Add( " a " , 100 );
5 context1.Variables.Add( " b " , 200 );
6 IDynamicExpression e1 = context1.CompileDynamic( " product(a,b) + sum(a,b) " );
7 int result = ( int )e1.Evaluate();
8  
9  
10 // 也可以添加一个别名,在编写表达式的时候带上前缀,调用自定义静态方法
11 ExpressionContext context2 = new ExpressionContext();
12 context2.Imports.AddType( typeof (CustomFunctions), " functions " );
13 IDynamicExpression e2 = context2.CompileDynamic( " functions.product(a,b) + a - b " );
14 result = ( int )e2.Evaluate();
15  
16  
17 // 引入实例
18 ExpressionContext context3 = new ExpressionContext();
19 context3.Variables.Add( " custom " , new CustomFunctions());
20 IDynamicExpression e3 = context3.CompileDynamic( " custom.Var_A + custom.Var_B " );
21 double result3 = ( double )e3.Evaluate();
22  
23  
24 // 构造表达式的执行环境
25 CustomFunctions rand = new CustomFunctions();
26 ExpressionContext context4 = new ExpressionContext(rand);
27 IDynamicExpression e4 = context4.CompileDynamic( " Var_A + Var_B " );
28 double result4 = ( double )e4.Evaluate();
 

转载于:https://www.cnblogs.com/luoyifan/archive/2010/10/14/1851254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值