脚踏实地,一步一个脚印,前进......

不抛弃,不放弃

导航

c#中实现类似js的Eval方法

using System;
using System.Collections;
using System.ComponentModel;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.JScript;
using System.Reflection;
//创建实现js中eval方法的类
public class EvalMethod
{
      //初始化加载程序的字符串;
      public static readonly String _jsClass = @"class theEval{ public function Eval(str:String):String {return eval(str)}}";
      //定义对象
      public static object _evalObject=null;
      public static Type _evalType =null;

      //构造函数
      static EvalMethod()
      {
            CodeDomProvider _provider = new JScriptCodeProvider();
            ICodeCompiler _iCode = _provider.CreateCompiler();
            CompilerParameters _parameter = new CompilerParameters();
            _parameters.GenerateInMemory = true;
            CompilerResult _result;
            _result = _iCode.CompilerAssemblyFromSource(_parameter,_jsClass);

            Assembly _assembly = _result.CompilerAssembly;
            _evalType = _assembly.GetType("theEval");
            _evalObject = Activator.CreateInstance(_evalType );
      }

public static object Eval(string str)
{
          return evalType .InvokeMember("Eval",BindingFlags.InvokeMethod,null,_evalobject,new object[]{str});
}
}

调用:
object _return = EvalMethod.Eval("2*4+14+2-4");

这样得到的效果基本上和js中的eval一样;

posted on 2008-06-30 11:08  沉默的人  阅读(993)  评论(0编辑  收藏  举报