熟悉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.'當然,代碼可以編譯通過,且執行是正常的。
下面我給出另外一種直接使用javascript的Eval函數的方法,借助于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; } }}
以上這篇關于動態執行代碼(js的Eval)實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答