熟悉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:WINDOWSMicrosoft.NETframeworkv1.1.4322Microsoft.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%system32msscript.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();
}
///
/// 引用com组件Microsoft script Control
/// %SystemRoot%system32msscript.ocx
/// 该函数用来动态执行代码
///
///
///
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)实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



