關於動態執行代碼(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平臺的好處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章