国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

關于動態執行代碼(js的Eval)實例詳解

2019-11-20 09:14:40
字體:
來源:轉載
供稿:網友

熟悉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)實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 会理县| 开平市| 中西区| 合山市| 曲麻莱县| 四平市| 朝阳市| 马龙县| 奉节县| 罗江县| 永宁县| 南开区| 正镶白旗| 苍溪县| 陆川县| 贵定县| 双城市| 四川省| 筠连县| 石林| 武清区| 台北市| 金平| 富源县| 浦江县| 突泉县| 凤山县| 南通市| 新竹县| 梅河口市| 黔东| 石首市| 张掖市| 通州市| 荣成市| 澄迈县| 镇江市| 玉田县| 宾川县| 乃东县| 建平县|