關于動態(tài)執(zhí)行代碼(js的Eval)實例詳解
熟悉javascript的朋友對Eval()函數可能都不會陌生,我們可以用它來實現動態(tài)代碼的執(zhí)行,我自己甚至寫過一個網頁專門用來計算算術表達式的,計算能力上比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)); } }
不過,令人不爽的是,編譯環(huán)境現在給出如下警告:'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.'當然,代碼可以編譯通過,且執(zhí)行是正常的。
下面我給出另外一種直接使用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 /// 該函數用來動態(tài)執(zhí)行代碼 /// </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; } } }
以上這篇關于動態(tài)執(zhí)行代碼(js的Eval)實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
微信小程序van-field中的left-icon屬性自定義實現過程
在小程序中,我們是用 Vant 組件庫時,常常會用到 van-field 輸入框控件,今天我將跟大家分享的是 van-field 輸入框控件中的 left-icon 屬性的自定義怎么實現,感興趣的朋友一起看看吧2023-08-08玩轉JavaScript函數:apply/call/bind技巧
歡迎來到這篇關于JavaScript中apply、call、bind函數的指南,這里充滿了實用技巧和深入理解,讓你的編程之旅更加游刃有余,趕快翻開這個神秘的“魔法書”,讓我們一起探索吧!2024-01-01