[英]Evaluating arithmetic expression with exponentiation from string
I need to evaluate arithmetic expression with exponentiation from string, for example: 我需要用来自字符串的幂来评估算术表达式,例如:
string expression = "4*5+2^3"
^ symbol could be change to any other symbol or string, but it have to be written in same way as + - * operations because numbers and operators are somewhat randomly generated. ^符号可以更改为任何其他符号或字符串,但是必须以与+-*操作相同的方式编写,因为数字和运算符在某种程度上是随机生成的。 Is there a way to do it?
有办法吗? I'm not sure you can write exponentiation operation this way in NCalc or Jace.Net
我不确定您是否可以在NCalc或Jace.Net中以这种方式编写幂运算
You can write Evaluator class as below to execute C# code dynamically: 您可以如下编写Evaluator类来动态执行C#代码:
public class Evaluator
{
public int Evaluate(string expression)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.ReferencedAssemblies.Add("system.dll");
compilerParameters.CompilerOptions = "/t:library";
compilerParameters.GenerateInMemory = true;
StringBuilder typeDefinition = new StringBuilder("");
typeDefinition.AppendLine("using System;");
typeDefinition.AppendLine("namespace Evaluator");
typeDefinition.AppendLine("{");
typeDefinition.AppendLine(" public class Evaluator");
typeDefinition.AppendLine(" {");
typeDefinition.AppendLine(" public object Evaluate()");
typeDefinition.AppendLine(" {");
typeDefinition.AppendLine(" return " + expression + ";");
typeDefinition.AppendLine(" }");
typeDefinition.AppendLine(" }");
typeDefinition.AppendLine("}");
CompilerResults compilerResult = codeProvider.CompileAssemblyFromSource(compilerParameters, typeDefinition.ToString());
System.Reflection.Assembly a = compilerResult.CompiledAssembly;
object o = a.CreateInstance("Evaluator.Evaluator");
Type dynamicEvaluatorType = o.GetType();
MethodInfo dynamicEvaluateMethod = dynamicEvaluatorType.GetMethod("Evaluate");
return (int) dynamicEvaluateMethod.Invoke(o, null);
}
}
Then you can use it like that: 然后,您可以像这样使用它:
string expression = "4*5+2";
int result = new Evaluator().Evaluate(expression);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.