字符串计算器
嗨其他程序员,
我在C#
创建一个计算器
我有一个字符串变量math
,其中包含100 * 5 - 2
如何在控制台中显示其输出498
?
我的代码是这样的:
String math = "100 * 5 - 2"; Console.WriteLine(math); Console.ReadLine(); // For Pause
所以基本上,我的代码给我的是字符串本身100 * 5 - 2
但我希望它能给我498
个结果。
关于这一点的想法非常感谢。
谢谢
可以使用DataTable.Compute
方法(来自MSDN )完成正则表达式评估:
计算通过筛选条件的当前行的给定表达式。
试试这个:
using System.Data;//import this namespace string math = "100 * 5 - 2"; string value = new DataTable().Compute(math, null).ToString();
试试吧
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 );
看到这个讨论
评估字符串“3 *(4 + 2)”产生int 18
更新:
如果这些值来自输入文本框,则以这种方式编写
String math = txtCalculator.Text.Trim(); int result = EvaluateExpression(math ); Console.WriteLine(result );
你也可以从这个讨论中找到一些非常好的答案
是否可以在.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(" ")) .CreateNavigator() .Evaluate(xsltExpression); // ReSharper restore PossibleNullReferenceException } }
试试这个
String math = (100*5-2).ToString(); Console.WriteLine(math);
演示
您可以在运行时从字符串编译代码并执行它:
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("2 + 2 * 2").Execute(); } } public class DynamicCalculator { 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 { { "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; } } }