zoukankan      html  css  js  c++  java
  • 在C#中实现类似Eval这类动态求值的函数【转载】

    这是一个很平常的需求,就好比说,给你一个字符串,1+2+3, 要动态计算它的结果。在VBS或者JAVASCRIPT这种脚本语言中,都有一个Eval方法。但在C#或者VB.NET中却没有。今天想起来研究一下,发现有朋友已经实现了。请参考下面的连接。很有意思的,呵呵

    本文转载自 http://www.cnblogs.com/kingthy/archive/2007/12/15/995641.html

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

    /// <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 }
                         );
            }
    /// <summary>
    ///
    /// </summary>
    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);
                      }
                  }";
        }

    这里还有一个更加复杂的实现方式

    http://www.cnblogs.com/michaelhuwei/archive/2007/12/29/1019658.html

    http://www.yaosansi.com/post/446.html

    还有一个更加好的例子

    http://www.codeproject.com/KB/cs/runtime_eval.aspx

    利用动态编译的机制实现

  • 相关阅读:
    Windows下安装使用OpenLDAP
    LDAP安装配置(windows)
    LDAP概念和原理介绍
    JDK自带的keytool证书工具详解
    递归算法讲解
    Creating an archive from a directory without the directory name being added to the archive
    Overview of the M&A Process
    Make sure base method gets called in C#
    How to delete specific nodes from an XElement?
    如何学习数据结构?
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1442037.html
Copyright © 2011-2022 走看看