现在的位置: 首页 > 综合 > 正文

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

2013年09月19日 ⁄ 综合 ⁄ 共 1263字 ⁄ 字号 评论关闭

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

使用方法
1.下载Noesis.Javascript.dll
2.Add Referene 加到工程
3.运行官方网站上给的Demo 
4.新建Console工程
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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noesis.Javascript;

namespace CSJS
{
    class Program
    {
        public class SystemConsole
        {
            public SystemConsole() { }

            public void Print(string iString)
            {
                Console.WriteLine(iString);
            }
        }

        static void Main(string[] args)
        {
            // Initialize a context
            JavascriptContext context = new JavascriptContext();

            // Setting external parameters for the context
            context.SetParameter("console", new SystemConsole());
            context.SetParameter("message", "Hello World !");
            context.SetParameter("number", 1);

            // Script
            string script = @"
    var i;
    for (i = 0; i < 5; i++)
        console.Print(message + ' (' + i + ')');
    number += i;
";

            // Running the script
            context.Run(script);

            // Getting a parameter
            Console.WriteLine("number: " + context.GetParameter("number"));
        }
    }
}

抱歉!评论已关闭.