是这个意思,把a,b,c的值带进去算下,然后得到的那个值就 199 但是由于那个是字符串形式的表达是 说白了,怎么解析它成 X = (a + b) * 0.2 + c + (a - c * 0.1 )这形式,这样程序是可以计算出结果199的,那怎么转换呢?听明白么
int a = 100; int b = 80; int c = 70; DataTable dt = new DataTable(); Console.WriteLine(Convert.ToInt32(dt.Compute(string.Format("({0} + {1}) * 0.2 + {2} + ({0} - {2} * 0.1 )",a,b,c), "")));
Expression Evaluator for C# based on Expression Tree http://www.codeproject.com/csharp/expression_evaluator.asp
但是由于那个是字符串形式的表达是
说白了,怎么解析它成 X = (a + b) * 0.2 + c + (a - c * 0.1 )这形式,这样程序是可以计算出结果199的,那怎么转换呢?听明白么
int b = 80;
int c = 70;
DataTable dt = new DataTable();
Console.WriteLine(Convert.ToInt32(dt.Compute(string.Format("({0} + {1}) * 0.2 + {2} + ({0} - {2} * 0.1 )",a,b,c), "")));
http://www.codeproject.com/csharp/expression_evaluator.asp
你的方法不错,但是我的那个表达式是随机生成的,也就是说自己事先是不知道的
所以就涉及到一个情况就是我不知道他里面有多少个X未知数了啊,那我这个表达式
string.Format("({0} + {1}) * 0.2 + {2} + ({0} - {2} * 0.1 )",a,b,c), "")怎么能动态写出来呢
public static object GetValue(string statement, string expressions)
{
string codeSnippet = "using System; " + "\r\n" +
"namespace SnippetCompiler {" + "\r\n" +
" public class Eval" + "\r\n" +
" {" + "\r\n" +
" public Eval(){} " + "\r\n" +
" public object GetValue()" + "\r\n" +
" {" + "\r\n" + statement + "\r\n" +
" return " + expressions + ";" + "\r\n" +
" }" + "\r\n" +
" } }";
CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(codeSnippet); ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters para = new CompilerParameters();
para.ReferencedAssemblies.Add("System.dll");
para.GenerateInMemory = true;
para.GenerateExecutable = false;
para.OutputAssembly = "Eval.dll"; Assembly asm = compiler.CompileAssemblyFromDom(para, unit).CompiledAssembly; Type type = asm.GetType("SnippetCompiler.Eval");
MethodInfo mi = type.GetMethod("GetValue", BindingFlags.Public | BindingFlags.Instance); object obj = asm.CreateInstance("SnippetCompiler.Eval");
return mi.Invoke(obj, null);
} static void Main(string[] args)
{
int a = 100,b = 80, c =70;
string statement = string.Format("int a={0},b = {1},c = {0};", a, b, c);
string expressions = "(a + b) * 0.2 + c + (a - c * 0.1 )";
Console.WriteLine(GetValue(statement,expressions).ToString());
}引自bobo0124(bobo0124) ( ) 信誉:97 Blog 稍作修改!结贴时记得也要感谢bobo0124哦!!
有这等事?哪有什么方法可以解决吗?
{
static void Main(string[] args)
{ string exp = "(a + b) * 0.2 + c + (a - c * 0.1 )";
//如果你的表达式的参数有规律的话(比如只是单个字母,从exp 中可解析出a,b,c等等,然后添加到ht中即可
Hashtable ht = new Hashtable();
ht.Add("a", 100);
ht.Add("b", 80);
ht.Add("c", 70);
Console.WriteLine(EvalExpression(exp, ht));
Console.ReadLine(); }
private static int EvalExpression(string Expression,Hashtable ht)
{
IDictionaryEnumerator en=ht.GetEnumerator();
while (en.MoveNext())
{
Expression = Expression.Replace(en.Key.ToString(), "{0}");
Expression = string.Format(Expression, Convert.ToInt32(en.Value));
}
DataTable dt = new DataTable();
return Convert.ToInt32(dt.Compute(Expression, ""));
}
}