简体   繁体   English

计算存储在字符串(C#)中的算术表达式

[英]evaluate an arithmetic expression stored in a string (C#)

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string. 我正在使用C#中的一个应用程序,在该应用程序中我想计算以字符串形式给出的算术表达式。 So like I got a string: 所以就像我得到一个字符串:

string myExpr="4*(80+(5/2))+2";

And I want to calculate the outcome of the arithmetic expression. 我想计算算术表达式的结果。 While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#. 当使用Javascript,PHP等语言时,您可以使用Eval来解决问题,这似乎不是C#中的选项。

I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so. 我想可以编写代码将其划分为无数个简单表达式,然后将它们计算并添加在一起,但这将花费相当长的时间,而在这样做的过程中可能会遇到很多麻烦。

So... my question, Is there any 'simple' way to do this? 所以...我的问题是,有什么“简单”的方法吗?

You could just call the JScript.NET eval function. 您可以只调用JScript.NET eval函数。 Any .NET language can call into any other. 任何.NET语言都可以调用任何其他语言。

There's a javascript library you can reference, then just do something like: 您可以参考一个JavaScript库,然后执行以下操作:

var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);

Edit; 编辑; Library is Microsoft.JScript 库是Microsoft.JScript

Have you seen http://ncalc.codeplex.com ? 您看过http://ncalc.codeplex.com吗?

It's extensible, fast (eg has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. 它可扩展,快速(例如,具有自己的缓存)使您能够通过处理EvaluateFunction / EvaluateParameter事件在运行时提供自定义函数和变量。 Example expressions it can parse: 它可以解析的示例表达式:

Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");

  e.Parameters["Pi2"] = new Expression("Pi * Pi");
  e.Parameters["X"] = 10;

  e.EvaluateParameter += delegate(string name, ParameterArgs args)
    {
      if (name == "Pi")
      args.Result = 3.14;
    };

  Debug.Assert(117.07 == e.Evaluate());

It also handles unicode & many data type natively. 它还可以本地处理unicode和许多数据类型。 It comes with an antler file if you want to change the grammer. 如果要更改语法,它附带一个鹿角文件。 There is also a fork which supports MEF to load new functions. 还有一个支持MEF加载新功能的fork。

It also supports logical operators, date/time's strings and if statements. 它还支持逻辑运算符,日期/时间的字符串和if语句。

See this answer: 看到这个答案:

C# Math calculator C#数学计算器

I've used NCalc with great success. 我使用NCalc取得了巨大的成功。 It's extremely flexible and allows for variables in your formulas. 它非常灵活,可以在公式中包含变量。 The formula you listed in your question could be evaluated this easily: 您在问题中列出的公式可以很容易地进行评估:

string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());

You need to implement an expression evaluator. 您需要实现一个表达式计算器。 It's fairly straightforward if you have the background, but it's not "simple". 如果您有背景,那将是相当简单的,但并非“简单”。 Eval in interpreted environments actually re-runs the language parser over the string; 解释环境中的Eval实际上会在字符串上重新运行语言解析器。 you need to emulate that operation, for the bits you care about, in your C# code. 您需要在C#代码中针对您关心的位模拟该操作。

Search for "expression evaluators" and "recursive descent parser" to get started. 搜索“表达式评估器”和“递归下降解析器”以开始使用。

If you have Bjarne Stroustrup's The C++ Programming Language , in Chapter 6 he explains step by step (in C++) how to do exactly what Chris Tavares suggests. 如果您有Bjarne Stroustrup的C ++编程语言 ,在第6章中,他将逐步(以C ++方式)解释Chris Tavares所建议的方法。

It's straightforward but a little heady if you're not familiar with the procedure. 这很简单,但是如果您不熟悉该过程,则会有些烦恼。

I needed to do something similar for an undergrad projectand I found this 我需要为本科生项目做类似的事情,我发现了这一点

Reverse Polish Notation In C# C#中的反向波兰语表示法

Tutorial and code to be extremely valuable. 教程和代码非常有价值。

It's pretty much just an implementation of converting the string to Reverse Polish Notation then evaluating it. 它几乎只是一种将字符串转换为反向波兰符号然后对其进行评估的实现。 It's extremely easy to use, understand and add new functions. 它非常易于使用,理解和添加新功能。 Source code is included. 包含源代码。

Try something like this: 尝试这样的事情:

int mySum = 4*(80+(5/2))+2;

var myStringSum = mySum.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM