Expression Evaluator

In my last c# project,  I need provide a special function, which is showing some menu items whose caption are not constant values. For example, an menu item's caption may be "Today(nov. 30)'s new blogs". The value "nov.30" will change to "Oct.1st" when the time goes.
So I developed a class(ExpressionEvaluator) to evaluate an expression like, "DateTime.Now.ToString()".
Here is my source code:

None.gif using  System;
None.gif
using  Microsoft.VisualBasic.Vsa;
None.gif
using  Microsoft.Vsa;
None.gif
using  System.Reflection;
None.gif
using  System.Collections;
None.gif
None.gif
namespace  MyComanyName.Utils
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 提供表达式求值静态方法。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class ExpressionEvaluator
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
nested class which implements IVsaSite#region nested class which implements IVsaSite
InBlock.gif
InBlock.gif        
class VsaSite:IVsaSite
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ArrayList _errors 
= new ArrayList();
InBlock.gif            
InBlock.gif            
public VsaSite()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public bool HasError
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return this._errors.Count>0;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public string Errors
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
get
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
string temp = "";
InBlock.gif
InBlock.gif                    
foreach(string str in _errors)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        temp 
+= str;
ExpandedSubBlockEnd.gif                    }

InBlock.gif
InBlock.gif                    
return temp;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif            
IVsaSite 成员#region IVsaSite 成员
InBlock.gif
InBlock.gif            
public object GetEventSourceInstance(string itemName, string eventSourceName)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// TODO:  添加 ExpressionEvaluator.GetEventSourceInstance 实现
InBlock.gif
                return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public object GetGlobalInstance(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// TODO:  添加 ExpressionEvaluator.GetGlobalInstance 实现
InBlock.gif
                return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public void Notify(string notify, object info)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// TODO:  添加 ExpressionEvaluator.Notify 实现
ExpandedSubBlockEnd.gif
            }

InBlock.gif
InBlock.gif            
public bool OnCompilerError(IVsaError e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this._errors.Add(string.Format("Error of severity {0}: {2}", e.Severity,  e.Description));
InBlock.gif                
return false;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
public void GetCompiledState(out byte[] pe, out byte[] debugInfo)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// TODO:  添加 ExpressionEvaluator.GetCompiledState 实现
InBlock.gif
                pe = null;
InBlock.gif                debugInfo 
= null;
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif            
#endregion

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 求值
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="str">表达式</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public static object Eval(string str)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
object result = null;
InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                IVsaEngine _engine 
= new Microsoft.VisualBasic.Vsa.VsaEngine();
InBlock.gif            
InBlock.gif                _engine.RootMoniker 
= "ExpressionScrip://eval/";
InBlock.gif                _engine.RootNamespace 
= "ExpressionScript";                
InBlock.gif                _engine.Site 
= new VsaSite();
InBlock.gif                _engine.InitNew();
InBlock.gif
InBlock.gif
InBlock.gif                IVsaItems items 
= _engine.Items;
InBlock.gif
InBlock.gif                IVsaReferenceItem   refItem;
InBlock.gif
InBlock.gif                
// Add system.dll
InBlock.gif
                refItem = (IVsaReferenceItem)items.CreateItem("system.dll",
InBlock.gif                    VsaItemType.Reference,
InBlock.gif                    VsaItemFlag.None);
InBlock.gif                refItem.AssemblyName 
= "system.dll";
InBlock.gif
InBlock.gif                
// Add mscorlib.dll
InBlock.gif
                refItem = (IVsaReferenceItem)items.CreateItem("mscorlib.dll",
InBlock.gif                    VsaItemType.Reference,
InBlock.gif                    VsaItemFlag.None);
InBlock.gif                refItem.AssemblyName 
= "mscorlib.dll";
InBlock.gif
InBlock.gif                IVsaCodeItem codeItem 
= (IVsaCodeItem)items.CreateItem("Script",VsaItemType.Code,VsaItemFlag.Class );
InBlock.gif                codeItem.SourceText 
= CreateClass(str);
InBlock.gif
InBlock.gif                
if(_engine.Compile())
InBlock.gif                    _engine.Run();
InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
throw new EvaluateException("Compile error:"+ (_engine.Site  as VsaSite).Errors);
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
// Execute the interface method. Using of ICloneable.Clone is just a trick.
InBlock.gif
                Assembly   assem = _engine.Assembly;
InBlock.gif                Type       type 
= assem.GetType("ExpressionScript.Expression");
InBlock.gif
InBlock.gif                
object o = Activator.CreateInstance(type);
InBlock.gif
InBlock.gif                
if(o is ICloneable)
InBlock.gif                    result 
= ( o as ICloneable).Clone();
InBlock.gif
InBlock.gif                _engine.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw ex;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return result;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private static string CreateClass(string str)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return @"imports System
InBlock.gif
                    imports System.Windows.Forms
InBlock.gif
InBlock.gif                    
' The name of the module must match the name of the code item
InBlock.gif
                    ' created in the hosting application via CreateItem.
InBlock.gif
                    Public Class Expression
InBlock.gif                        Implements ICloneable
InBlock.gif
InBlock.gif                        Public Overridable Function Clone() As Object Implements System.ICloneable.Clone
InBlock.gif                            Return 
"+str+@"
InBlock.gif                        End Function
InBlock.gif                    End Class
InBlock.gif                    
";
ExpandedSubBlockEnd.gif
        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public class EvaluateException:System.Exception
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public EvaluateException(string msg):base(msg)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{}
InBlock.gif
InBlock.gif        
public EvaluateException(string msg,System.Exception e):base(msg,e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{}
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


 

转载于:https://www.cnblogs.com/mahope/archive/2004/11/30/70989.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Expression Evaluator 是一个用 Java 编写的库,可以解析和计算数学表达式,并支持自定义函数和变量。它可以用于在 Java 应用程序中动态计算数学表达式,例如计算器或科学计算应用程序。使用 Java Expression Evaluator,您可以轻松地解析和计算包含各种数学函数和运算符的表达式,并在运行时添加自定义函数和变量。 Java Expression Evaluator 支持各种数学函数和运算符,例如加法、减法、乘法、除法、幂运算、三角函数、对数函数等。它还支持自定义函数和变量,您可以在运行时添加自己的函数和变量,并将它们包含在表达式中计算。 Java Expression Evaluator 的使用非常简单。您只需要创建一个 ExpressionEvaluator 对象,然后使用 evaluate() 方法计算表达式。例如: ``` ExpressionEvaluator ee = new ExpressionEvaluator(); double result = ee.evaluate("2 + 3 * 4"); ``` 以上代码将计算表达式 2 + 3 * 4,结果为 14。您也可以添加自定义函数和变量,例如: ``` ExpressionEvaluator ee = new ExpressionEvaluator(); ee.putFunction("square", new Function() { public double apply(double... args) { return args[0] * args[0]; } }); ee.putVariable("x", 5); double result = ee.evaluate("square(x) + 3"); ``` 以上代码将添加一个名为 square 的自定义函数,该函数计算参数的平方。然后,它将添加一个名为 x 的变量,并将其设置为 5。最后,它将计算表达式 square(x) + 3,结果为 28。 Java Expression Evaluator 是一个非常有用的库,可以帮助您轻松地解析和计算数学表达式,并支持自定义函数和变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值