关于动态执行代码(js的Eval)

        熟悉javascript的朋友对Eval()函数可能都不会陌生,我们可以用它来实现动态代码的执行,我自己甚至写过一个网页专门用来计算算术表达式的,计算能力上比google、baidu的

计算器还要好一些,至少精度要高,但是如果超出了四则运算的话,表达式的形式会复杂很,比如以百度给出的例子:

log((5+5)^2)-3+pi需要写成Math.log(Math.pow(5+5,2))*Math.LOG10E-3+Math.PI才能用Eval进行计算,对于这一点我还没有想到理想的解决方案。好了,这不是本文正题,我们姑且放过。

        博客园里曾经见人用过下面的代码,至少从代码形式上挺简单的:

// csc.exe noname1.cs /r:C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.JScript.dll
//注:需加入Microsoft.JScript与Microsoft.Vsa两个命名空间。
public class Class1
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World");
        string Expression = "var result:int =0;result==1?\"成功\":\"失败\"";
        Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
        Console.WriteLine(Microsoft.JScript.Eval.JScriptEvaluate(Expression, ve));
    }
}

        不过,令人不爽的是,编译环境现在给出如下警告:'Microsoft.JScript.Vsa.VsaEngine' is obsolete: 'Use of this type is not recommended because it is being deprecated in Visual Studio 2005;

 there will be no replacement for this feature. Please see the ICodeCompiler documentation for additional help.'当然,代码可以编译通过,且执行是正常的。

       下面我给出另外一种直接使用javascriptEval函数的方法,借助于com组件,引用路径是 %SystemRoot%\system32\msscript.ocx ,我将完整的代码直接贴出来。

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ScriptProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            string strExpression = "1+2*3";
            string strResult = Eval(strExpression);
            Console.WriteLine(strExpression + "=" + strResult);
 
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
        /// <summary>
        /// 引用com组件Microsoft Script Control
        /// %SystemRoot%\system32\msscript.ocx
        /// 该函数用来动态执行代码
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static string Eval(string Expression)
        {
            string strResult = null;
            try
            {
                MSScriptControl.ScriptControlClass jscript = new MSScriptControl.ScriptControlClass();
                jscript.Language = "JScript";               
                strResult = jscript.Eval(Expression).ToString();
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.Message);              
            }
            return strResult;
        }
    }
}

以上内容来自:http://www.cnblogs.com/flappy/archive/2006/05/14/399803.html

不过本人也想到另外一种方式实现这个公式的计算。就是使用MS的JScript语言,写好函数,再使用命令:jsc /t:library 文件名.js 直接输出成动态链接库,这就是使用.NET平台的好处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值