【问题标题】:Evaluating a mathematical expression评估数学表达式
【发布时间】:2013-11-27 05:07:54
【问题描述】:

伙计们,我正在评估一个字符串数学表达式。

首先我导入了库

using System.Linq.Expressions;

然后在我的代码中,我做了,

Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
  double result = e.Evaluate();

但是我得到的错误是 无法创建抽象类或接口“System.Linq.Expressions.Expression”的实例

为什么上述方法不起作用?

我该如何评估?

【问题讨论】:

  • 您为什么希望它能够工作?您是否阅读过您尝试实例化的类型的文档?
  • @Asad 我期待它能够工作,因为我在之前的一篇文章中提出了这个解决方案。
  • C#中没有方法,比如javascript的"eval方法是

标签: c# expression calculator evaluation


【解决方案1】:

为了在 c# 中计算这样的表达式,您必须使用 Roslyn。这是一个示例(我更改了一段代码,取自这里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);");
        }
    }
}

表达式只允许您从代码创建语法树:

Expression<Func<int,int,int>> add = (x, y) => x + y;
var res = add.Compilie()(2,3);

所以你不能使用字符串作为表达式的来源,你必须把它写成一个有效的c#代码。

【讨论】:

    【解决方案2】:

    尝试使用NCalc

    Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
    double result = e.Evaluate();
    

    http://ncalc.codeplex.com/

    【讨论】:

      【解决方案3】:

      我选择了 Ncalc。 我将我的代码发布给将来会遇到和我一样的问题的用户。

      1.下载Ncalc(Binaries)http://ncalc.codeplex.com/releases/view/73656

      1. 在您的解决方案中引用 dll。(右键单击 > 添加引用 > 浏览 > NCalc.dll)
      2. 在代码中

        使用 NCalc;

      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;
      
              }
      

      【讨论】:

        【解决方案4】:

        您可以使用Mathos Parser。它是一个简单的 .NET 数学表达式解析器。

        【讨论】:

          猜你喜欢
          • 2010-12-05
          • 1970-01-01
          • 2011-06-30
          • 2010-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多