[英]Evaluating a mathematical expression
Guys I am up with evaluating a string mathematical expression. 伙计们,我正在评估一个字符串数学表达式。
First I imported the library 首先我导入了图书馆
using System.Linq.Expressions;
Then in my codes I did, 然后在我的代码中,
Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
double result = e.Evaluate();
however I get the error as Cannot create an instance of the abstract class or interface 'System.Linq.Expressions.Expression' 但是由于无法创建抽象类或接口'System.Linq.Expressions.Expression'的实例而收到错误
Why the above is not working? 为什么以上方法不起作用?
How can I evaluate this ? 我该如何评估?
In order to evaluate expressions like this in c#, you have to use Roslyn. 为了在c#中评估这样的表达式,您必须使用Roslyn。 Here's an example (I changed a piece of code take from here http://blogs.msdn.com/b/csharpfaq/archive/2011/12/02/introduction-to-the-roslyn-scripting-api.aspx ):
这是一个示例(我从此处http://blogs.msdn.com/b/csharpfaq/archive/2011/12/02/introduction-to-the-roslyn-scripting-api.aspx更改了一段代码):
using Roslyn.Scripting.CSharp;
namespace RoslynScriptingDemo {
class Program {
static void Main(string[] args) {
var engine = new ScriptEngine();
engine.Execute(@"System.Console.WriteLine((450*5)+((3.14*7)/50)*100);");
}
}
}
Expressions only let you to create a syntax tree from code: 表达式仅允许您从代码创建语法树:
Expression<Func<int,int,int>> add = (x, y) => x + y;
var res = add.Compilie()(2,3);
So you can't use string as a source for expression, you have to write it as a valid c# code. 因此,您不能将字符串用作表达式的源,而必须将其编写为有效的C#代码。
Try to use NCalc : 尝试使用NCalc :
Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
double result = e.Evaluate();
I went for Ncalc. 我去了Ncalc。 I am posting my codes for future users who will be on same problems like me.
我正在将代码发布给将来的用户,这些用户将像我一样遇到同样的问题。
1.Download the Ncalc(Binaries) http://ncalc.codeplex.com/releases/view/73656 1.下载Ncalc(二进制文件) http://ncalc.codeplex.com/releases/view/73656
In codes 在代码中
Using NCalc; 使用NCalc;
3.May be used as 3.可以用作
public Double Calculate(string argExpression)
{
//get the user passed string
string ExpressionToEvaluate = argExpression;
//pass string in the evaluation object declaration.
Expression z = new Expression(ExpressionToEvaluate);
//command to evaluate the value of the **************string expression
var result = z.Evaluate();
Double results = Convert.ToDouble(result.ToString());
return results;
}
You can use Mathos Parser . 您可以使用Mathos Parser 。 It is a simple .NET Mathematical Expression parser.
这是一个简单的.NET数学表达式解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.