如何在C#中运行数学表达式字符串
作者:互联网
如何在C#中运行数学表达式字符串
方法1:利用DataTable中的Compute方法
1 string expression = "1+2*3"; 2 DataTable eval = new DataTable();object result = eval.Compute(expression, “”);
方法2:利用xPath表达式
1 publicstaticdoubleEvaluate(string expression) 2 { 3 return(double)newSystem.Xml.XPath.XPathDocument 4 (newStringReader("")).CreateNavigator().Evaluate 5 (string.Format("number({0})",new 6 System.Text.RegularExpressions.Regex(@"([\+\-\*])") 7 .Replace(expression," ${1} ") 8 .Replace("/"," div ") 9 .Replace("%"," mod "))); 10 }
//方法3:利用python里面的计算表达式方法
View Code
方法4:在网上找了一个计算表达式的类库
/// <summary> /// 动态求值 /// </summary> public class Evaluator { /// <summary> /// 计算结果,如果表达式出错则抛出异常 /// </summary> /// <param name="statement">表达式,如"1+2+3+4"</param> /// <returns>结果</returns> public static object Eval(string statement) { return _evaluatorType.InvokeMember( "Eval", BindingFlags.InvokeMethod, null, _evaluator, new object[] { statement } ); } /// <summary> /// /// </summary> static Evaluator() { //构造JScript的编译驱动代码 CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript"); CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = provider.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); } private static object _evaluator = null; private static Type _evaluatorType = null; /// <summary> /// JScript代码 /// </summary> private static readonly string _jscriptSource = @"class Evaluator { public function Eval(expr : String) : String { return eval(expr); } }"; }
标签:string,parameters,C#,static,字符串,new,Evaluator,表达式 来源: https://www.cnblogs.com/devgis/p/16480161.html