C#执行Javascript代码的几种方法总结
时间:2022-05-03 10:56:52|栏目:.NET代码|点击: 次
一、开源项目 Javascript .NET
地址: http://javascriptdotnet.codeplex.com/ 它是Google Chrome V8引擎在.NET上的封装,功能完善,性能相对较高,推荐使用! (缺点就是asp.net web应用上,好象会报错)
示例代码:
复制代码 代码如下:
using Noesis.Javascript;
using System;
using System.Collections.Generic;
namespace JsCSharp
{
class Program
{
static void Main(string[] args)
{
using (JavascriptContext ctx = new JavascriptContext())
{
var i = ctx.Run("1+2");
Console.WriteLine(i);//3
ctx.Run("var d = new Date(2013,9-1,2,20,30,15)");
var d = ctx.GetParameter("d");
Console.WriteLine(d);//2013/9/2 20:30:15
var j = ctx.Run("function add(x,y){return x+y;};add(5,10);");
Console.WriteLine(j);//15
ctx.Run("var obj = {};obj.name='jimmy';obj.sex='Male';obj.name='杨俊明'");
var obj = ctx.GetParameter("obj") as Dictionary<string, object>;
foreach (var key in obj.Keys)
{
Console.WriteLine(string.Format("{0}:{1}", key, obj[key]));
//name:杨俊明
//sex:Male
}
var jsonArr = ctx.Run("[{Airport:'PEK',Name:'北京首都机场'},{Airport:'XIY',Name:'西安咸阳机场'}]") as Array;
foreach (var item in jsonArr)
{
var json = item as Dictionary<string, object>;
foreach (var key in json.Keys)
{
Console.WriteLine(string.Format("{0}:{1}", key, json[key]));
//Airport:PEK
//Name:北京首都机场
//Airport:XIY
//Name:西安咸阳机场
}
}
ctx.SetParameter("x", 7);
ctx.Run("function add(x,y){return x+y;}; function sub(x,y){return x-y;};k = add(2,x);var t = sub(9,1);");
var k = ctx.GetParameter("k");
Console.WriteLine(k);//9
var t = ctx.GetParameter("t");
Console.WriteLine(t);//8
Console.Read();
}
}
}
}
部署时要注意,msvcp100.dll、msvcr100.dll这二个文件,要复制到bin目录下
二、利用Microsoft.JScript.Vsa
先添加Microsoft.JScript、Microsoft.Vsa二个程序集的引用,然后就能用了,示例代码如下:
复制代码 代码如下:
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using System;
namespace JsCSharp
{
class Program
{
static VsaEngine Engine = VsaEngine.CreateEngine();
static void Main(string[] args)
{
var i = (int)EvalJScript("1+2;");
Console.WriteLine(i);//3
var d = (DateObject)EvalJScript("var d = new Date(2013,9-1,2,20,30,15)");
Console.WriteLine(d);//Mon Sep 2 20:30:15 UTC+8 2013
var j = EvalJScript("function add(x,y){return x+y;};add(5,10);");
Console.WriteLine(j);//15
var obj = EvalJScript("var obj = {};obj.name='jimmy';obj.sex='Male';");
Console.WriteLine(obj);//Male 注:只返回最后一条执行的语句结果
Console.Read();
}
static object EvalJScript(string JScript)
{
object Result = null;
try
{
Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
}
catch (Exception ex)
{
return ex.Message;
}
return Result;
}
}
}
Vsa的功能比较有限,多条语句执行时,只返回最后一条语句的执行结果。
栏 目:.NET代码
本文地址:http://www.codeinn.net/misctech/200855.html