首页 > 代码库 > C#运算String型表达式

C#运算String型表达式

现在有一个小需求就是一个xml中有一个condition节点,节点中包含有一个字符串类型的表达式,要对这个表达式进行运算,判断运算结果是true还是false。

如下:

  <Condition Type="CONDITION">param1>3</Condition>

现需要运算condition中的表达式param1>3。表达式的语法符合javascript表达式语法。

 

解决的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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();
}
 
}
}