【问题标题】:Convert a string to an operator? [duplicate]将字符串转换为运算符? [复制]
【发布时间】:2012-12-20 14:37:54
【问题描述】:

可能重复:
Is there a string math evaluator in .NET?

有没有一种方法可以在不检查"+", "-", "*", "/" 然后传递值的情况下转换操作符代码?

using System;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main(string[] args)
        {
            string operator = "+";
            int inputOne = 2;
            int inputTwo = 5;

            Console.WriteLine(Result(inputOne, inputTwo, operator));
            Console.ReadLine();
        }


        public static string Result(int one, int two, string computeOperator)
        {
            if (computeOperator == "+")
            {
                return (one + two).ToString();
            }

            if (computeOperator == "-")
            {
                return (one - two).ToString();
            }

            //and so on...

            return "0";
        }
    }
}

【问题讨论】:

  • 找一个好的数学表达式解析器。
  • 你可以传递一个委托,例如Func<int, int, int>
  • 您最终将实现一个具有两个堆栈的功能齐全的计算器。

标签: c# .net string


【解决方案1】:

,不是您想要的方式。根据定义,string literal 不能转换为运算符。

【讨论】:

  • 我不知道。 @Dan Andrews 在上面发布的链接中有几种可能的方法。
  • @DavidStratton 在后台,这些可能的方法正在执行类似于 OP 正在执行的方式的字符串比较。他们不会将字符串文字转换为运算符。
  • 你是对的。我想我只是在看最终结果-“他能否通过采用不同的方法来实现他想要的(取一个显然是数学表达式的字符串并计算它)”,而不是“他能否使用该方法实现他想要的他是特意询问的”。但是您指出他所询问的方法行不通是对的。有时我太专注于最终结果,以至于忘记了如何到达那里。我有时需要改进的东西。我敢打赌,如果我确实更加关注如何到达那里,我会成为一个更好的编码员。 ;-)
【解决方案2】:

您的问题类似于example sample of lexical analyzer in c#。您可以尝试使用其中一种词法分析器,但除非您要解析大量文本,否则可能不值得。

作为参考,这可能是该答案中最相关的链接...

Lucene Text Analyzer - C# | CodeProject

【讨论】:

    【解决方案3】:

    只是。 但是你可以使用Eval进行计算

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2013-02-16
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多