将字符串转换为运算符?

时间:2012-12-20 14:37:55

标签: c# .net string

  

可能重复:
  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";
        }
    }
}

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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

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

Lucene Text Analyzer - C# | CodeProject

答案 2 :(得分:0)

只需。 但您可以使用Eval

进行计算
相关问题