字符串计算器

时间:2014-02-22 05:20:11

标签: c# console-application calculator

嗨其他程序员,

我正在C#

创建一个计算器

我有一个字符串变量math,其中包含100 * 5 - 2

如何在控制台中显示498的输出?

我的代码是:

String math = "100 * 5 - 2"; 

Console.WriteLine(math);

Console.ReadLine(); // For Pause

基本上,我的代码给我的是字符串本身100 * 5 - 2

但我希望它能为我提供498

对此非常感激。

由于

3 个答案:

答案 0 :(得分:14)

正则表达式评估可以使用DataTable.Compute方法(来自MSDN):

完成
  

计算通过过滤器的当前行的给定表达式   标准。

试试这个:

using System.Data;//import this namespace

 string math = "100 * 5 - 2";
 string value = new DataTable().Compute(math, null).ToString();

答案 1 :(得分:2)

只需尝试这个

String math = (100 * 5 - 2).ToString(); 

我不知道,为什么你想要更复杂?这很容易......

如果你确定如此,你可以使用EvaluateExpression

来做到这一点
public int EvaluateExpression(string math )
    {
       return Convert.ToInt32(math);
    }

........................

String math = "100 * 5 - 2"; 

int result = EvaluateExpression(math );

Console.WriteLine(result );

参见此讨论

Evaluating string "3*(4+2)" yield int 18

<强>更新

如果这些值来自输入文本框,则以这种方式编写

String math = txtCalculator.Text.Trim();

    int result = EvaluateExpression(math );

    Console.WriteLine(result );

你也可以从这次讨论中找到一些非常好的答案

Is it possible to compile and execute new code at runtime in .NET?

更新2:

最后,我为你试了这个样本:

我的类库的完整代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.XPath;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String math = "100 * 5 - 2";

        Console.WriteLine(Evaluate(math));
    }

    public static double Evaluate(string expression)
    {
        var xsltExpression =
            string.Format("number({0})",
                new Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
                                        .Replace("/", " div ")
                                        .Replace("%", " mod "));

        // ReSharper disable PossibleNullReferenceException
        return (double)new XPathDocument
            (new StringReader("<r/>"))
                .CreateNavigator()
                .Evaluate(xsltExpression);
        // ReSharper restore PossibleNullReferenceException
    }
}

答案 2 :(得分:0)

您可以在运行时从字符串编译代码并执行它:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DynamicCalcTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = new DynamicCalculator<double>("2 + 2 * 2").Execute();
        }
    }


    public class DynamicCalculator<T>
    {
        private MethodInfo _Method = null;

        public DynamicCalculator(string code)
        {
            _Method = GetMethodInfo(code);
        }

        public T Execute()
        {
            return (T)_Method.Invoke(null, null);
        }

        private MethodInfo GetMethodInfo(string code)
        {
            var tpl = @"
                public static class Calculator
                {{
                    public static double Calc()
                    {{
                        return {0};
                    }}
                }}";

            var finalCode = string.Format(tpl, code);

            var parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.GenerateInMemory = true;
            parameters.CompilerOptions = "/platform:anycpu";

            var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" }     };

            var c = new CSharpCodeProvider(options);
            var results = c.CompileAssemblyFromSource(parameters, finalCode);

            var type = results.CompiledAssembly.GetExportedTypes()[0];
            var mi = type.GetMethod("Calc");
            return mi;
        }
    }
}
相关问题