C# Javascript引擎,如何在C#中执行现有的JS代码?

来源:互联网 发布:适合程序员的网站 编辑:程序博客网 时间:2024/05/20 04:49

请下载这个Assembly。提供了.net3.5和.net4.0版本


使用方法
1.下载Noesis.Javascript.dll
2.Add Referene 加到工程
3.运行官方网站上给的Demo 
4.新建Console工程
[csharp] view plaincopy
  1. CSJS  
后附完整代码:
运行后可获得命令行输出。

http://javascriptdotnet.codeplex.com/

这个是对Google's V8 Javascript engine的封装,最好的Javascript引擎了。有了这个我们就可以将一些现有的Javascirpt代码引入到C#的代码中运行了。

Project Description

Javascript .NET integrates Google's V8 Javascript engine and exposes it to the CLI environment. Javascript .NET compiles (at runtime) and executes scripts directly from .NET code. It allows CLI objects to be exposed and manipulated directly from the executed Javascript.

Sample "Hello World" running through Javascript

[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Noesis.Javascript;  
  6.   
  7. namespace CSJS  
  8. {  
  9.     class Program  
  10.     {  
  11.         public class SystemConsole  
  12.         {  
  13.             public SystemConsole() { }  
  14.   
  15.             public void Print(string iString)  
  16.             {  
  17.                 Console.WriteLine(iString);  
  18.             }  
  19.         }  
  20.   
  21.         static void Main(string[] args)  
  22.         {  
  23.             // Initialize a context  
  24.             JavascriptContext context = new JavascriptContext();  
  25.   
  26.             // Setting external parameters for the context  
  27.             context.SetParameter("console"new SystemConsole());  
  28.             context.SetParameter("message""Hello World !");  
  29.             context.SetParameter("number", 1);  
  30.   
  31.             // Script  
  32.             string script = @"  
  33.     var i;  
  34.     for (i = 0; i < 5; i++)  
  35.         console.Print(message + ' (' + i + ')');  
  36.     number += i;  
  37. ";  
  38.   
  39.             // Running the script  
  40.             context.Run(script);  
  41.   
  42.             // Getting a parameter  
  43.             Console.WriteLine("number: " + context.GetParameter("number"));  
  44.         }  
  45.     }  
  46. }  


原文:

http://blog.csdn.net/iamoyjj/article/details/6677189