欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于動(dòng)態(tài)執(zhí)行代碼(js的Eval)實(shí)例詳解

 更新時(shí)間:2016年08月15日 10:08:11   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇關(guān)于動(dòng)態(tài)執(zhí)行代碼(js的Eval)實(shí)例詳解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

熟悉javascript的朋友對(duì)Eval()函數(shù)可能都不會(huì)陌生,我們可以用它來(lái)實(shí)現(xiàn)動(dòng)態(tài)代碼的執(zhí)行,我自己甚至寫過(guò)一個(gè)網(wǎng)頁(yè)專門用來(lái)計(jì)算算術(shù)表達(dá)式的,計(jì)算能力上比google、baidu的計(jì)算器還要好一些,至少精度要高,但是如果超出了四則運(yùn)算的話,表達(dá)式的形式會(huì)復(fù)雜很,比如以百度給出的例子:

log((5+5)^2)-3+pi需要寫成Math.log(Math.pow(5+5,2))*Math.LOG10E-3+Math.PI才能用Eval進(jìn)行計(jì)算,對(duì)于這一點(diǎn)我還沒(méi)有想到理想的解決方案。好了,這不是本文正題,我們姑且放過(guò)。

博客園里曾經(jīng)見(jiàn)人用過(guò)下面的代碼,至少?gòu)拇a形式上挺簡(jiǎn)單的:

// csc.exe noname1.cs /r:C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.JScript.dll 
//注:需加入Microsoft.JScript與Microsoft.Vsa兩個(gè)命名空間。
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));
  }
}

不過(guò),令人不爽的是,編譯環(huán)境現(xià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.'當(dāng)然,代碼可以編譯通過(guò),且執(zhí)行是正常的。

下面我給出另外一種直接使用javascript的Eval函數(shù)的方法,借助于com組件,引用路徑是 %SystemRoot%\system32\msscript.ocx ,我將完整的代碼直接貼出來(lái)。

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
    /// 該函數(shù)用來(lái)動(dòng)態(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;
    }
  }
}

以上這篇關(guān)于動(dòng)態(tài)執(zhí)行代碼(js的Eval)實(shí)例詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論