本文介绍在C#中动态执行JavaScript代码的两种方法。首先分析使用Microsoft.JScript.Vsa.VsaEngine的方式及其过时警告问题,随后重点讲解通过引用msscript.ocx组件调用Eval函数的实现方案。代码示例展示了如何处理算术表达式及复杂数学运算,为需要动态脚本解析的场景提供参考。
动态执行JavaScript代码概述
熟悉JavaScript的朋友对Eval()函数应该不陌生,它可用于实现动态代码执行。笔者曾编写网页专门计算算术表达式,其精度优于Google和Baidu的在线计算器。然而,当表达式超出基础四则运算时,形式会变得复杂。例如百度给出的例子:
log((5+5)^2)-3+pi需要写成Math.log(Math.pow(5+5,2))*Math.LOG10E-3+Math.PI才能用Eval进行计算。对此笔者尚未找到理想的解决方案。但这并非本文重点,暂且不论。
VsaEngine方案及过时警告
博客园中有人使用过以下代码,从形式上看较为简单:
// 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.'。尽管代码能编译通过且执行正常,该警告仍令人困扰。
基于MSScript.ocx的Eval实现
下面介绍另一种直接使用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)的实例详解就是全部内容,希望能给大家提供参考,也希望大家多多支持本站。