Is there a string math evaluator in .NET?

前端 未结 16 1702
长情又很酷
长情又很酷 2020-11-22 01:01

If I have a string with a valid math expression such as:

String s = \"1 + 2 * 7\";

Is there a built in library/function in .NET that will p

16条回答
  •  独厮守ぢ
    2020-11-22 01:35

    Yet another option now that Roslyn is available:

    You can use CodeAnalysis.CSharp.Scripting library for this.

    using Microsoft.CodeAnalysis.CSharp.Scripting;
    using System;
    
    namespace ExpressionParser
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Demonstrate evaluating C# code
                var result = CSharpScript.EvaluateAsync("System.DateTime.Now.AddDays(-1) > System.DateTime.Now").Result;
                Console.WriteLine(result.ToString());
    
                //Demonstrate evaluating simple expressions
                var result2 = CSharpScript.EvaluateAsync(" 5 * 7").Result;
                Console.WriteLine(result2);
                Console.ReadKey();
            }
        }
    }
    

    nuget packages:

    
    
    
    
    
    
    

提交回复
热议问题