• Eval C#表达式计算


    Console.WriteLine(Evaluator.Eval("1+2+3+4+5+6+7+8+9"));//45
    Console.WriteLine(Evaluator.Eval("(1+1)/2*3"));
    Console.WriteLine(Evaluator.Eval("((10-2)/2+1)*3"));//15
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using System.CodeDom.Compiler;
    using System.Reflection;

    namespace Eval_Demo
    {
        
    /// <summary>
        
    /// 动态求值
        
    /// </summary>
        public class Evaluator
        {
            
    /// <summary>
            
    /// 计算结果,如果表达式出错则抛出异常
            
    /// </summary>
            
    /// <param name="statement">表达式,如"1+2+3+4"</param>
            
    /// <returns>结果</returns>
            public static object Eval(string statement)
            {
                
    return _evaluatorType.InvokeMember(
                            
    "Eval",
                            BindingFlags.InvokeMethod,
                            
    null,
                            _evaluator,
                            
    new object[] { statement }
                         );
            }

            
    static Evaluator()
            {
                
    //构造JScript的编译驱动代码
                CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");

                CompilerParameters parameters;
                parameters 
    = new CompilerParameters();
                parameters.GenerateInMemory 
    = true;

                CompilerResults results;
                results 
    = provider.CompileAssemblyFromSource(parameters, _jscriptSource);

                Assembly assembly 
    = results.CompiledAssembly;
                _evaluatorType 
    = assembly.GetType("Evaluator");

                _evaluator 
    = Activator.CreateInstance(_evaluatorType);
            }

            
    private static object _evaluator = null;
            
    private static Type _evaluatorType = null;

            
    /// <summary>
            
    /// JScript代码
            
    /// </summary>
            private static readonly string _jscriptSource =
                
    @"class Evaluator
                  {
                      public function Eval(expr : String) : String 
                      { 
                         return eval(expr); 
                      }
                  }
    ";
        }

    } 

  • 相关阅读:
    第四章 数组和方法
    JAVA基础笔记
    ios navigationcontroller add multi navigationItem
    Objective-C Runtime能做什么?
    在Xcode中使用Git进行源码版本控制
    分析iOS Crash文件:符号化iOS Crash文件的3种方法
    Core Animation Layer(22)
    Touch Events and UIResponder(19)
    UIPopoverController and Modal View Controllers(13)
    Subclassing UITableViewCell(15)
  • 原文地址:https://www.cnblogs.com/RobotTech/p/2098717.html
Copyright © 2020-2023  润新知