【问题标题】:String calculator [closed]字符串计算器[关闭]
【发布时间】:2014-03-23 21:24:42
【问题描述】:

各位程序员,

我正在C#创建一个计算器

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

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

我的代码是这样的:

String math = "100 * 5 - 2"; 

Console.WriteLine(math);

Console.ReadLine(); // For Pause

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

但我希望它给我498

对此的想法非常感谢。

谢谢

【问题讨论】:

标签: c# console-application calculator


【解决方案1】:

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

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

试试这个:

using System.Data;//import this namespace

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

【讨论】:

  • 是的.. 我刚看到。完美!
  • 它工作正常吗?
  • 请记住DataTable.Compute() 不适用于单声道(可能是由于某些单声道实现错误)。
【解决方案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
    }
}

【讨论】:

  • 我猜 OP 也想评估用户输入
  • @pcnThird ,也可以,但是 OP 没有提到这一点。
  • 您好先生,如果该值来自基本上是字符串的文本框怎么办,对吧?
  • @GM-XileGM-Xile:你的意思是字符串"100 * 5 - 2"来自文本框?对吗?
  • 当前上下文中不存在名称 EvaluateExpression。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2014-04-02
    相关资源
    最近更新 更多