C#运算String型表达式
现在有一个小需求就是一个xml中有一个condition节点,节点中包含有一个字符串类型的表达式,要对这个表达式进行运算,判断运算结果是true还是false。
如下:
<Condition Type="CONDITION">param1>3</Condition>
现需要运算condition中的表达式param1>3。表达式的语法符合javascript表达式语法。
解决的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.JScript; namespace TestXpression { class Program { /// <summary> /// 微软提供的运算符合js语法的表达式 /// </summary> /// <param name="sExpression"></param> /// <returns></returns> public static object EvalExpress(string sExpression) { Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine(); return Microsoft.JScript.Eval.JScriptEvaluate(sExpression, ve); } /// <summary> /// 传入参数,将参数和参数值进行拼接 /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> public static string trans(string name, string value,string type) { string s = ""; //"var a=10;var b=15;var c='hello'" //string s = "var " + name + "=" + value.ToString() + ";"; if (type == "stringType") { s = "var " + name + "=" + "'" + value.ToString() + "'" + ";"; } else { s = "var " + name + "=" + value.ToString() + ";"; } return s; } public static string MakeCondition() { Dictionary<string, string> myParameters = new Dictionary<string, string>(); myParameters.Add("xingCan1", "15"); myParameters.Add("xingCan2", "10"); myParameters.Add("xingCan3","C"); string condition = ""; string type = "stringType"; foreach (var ss in myParameters) { condition += trans(ss.Key.ToString(), ss.Value.ToString(), type); } string expression1 = "xingCan1>xingCan2"; string expression2 = "xingCan3=='C'"; // ------------参数赋值--------------------------- <<<<条件>>>>> //"var xingCan1=10;var xingCan2=15;var xingCan3='C';xingCan3=='C'" condition += expression1; return condition; } static void Main(string[] args) { string s = MakeCondition(); object flag = EvalExpress(s); System.Console.WriteLine(flag.ToString()); System.Console.ReadLine(); } } }