之前我介绍过一个开源的.Net下的Javascript引擎Javascript .NET,今天发现微软自己也开源了一个JavaScript引擎——ClearScript(当然,也支持VB Script)。
由于是微软发布的,基本上没有什么好挑剔的地方,稳定而强大,不过不支持WinRT。下面这个则是官方示例,就不做更多介绍了,感兴趣的朋友可以去CodePlex看下。

1 using System; 2 using Microsoft.ClearScript; 3 using Microsoft.ClearScript.V8; 4 5 // create a script engine 6 using (var engine = new V8ScriptEngine()) 7 { 8 // expose a host type 9 engine.AddHostType("Console", typeof(Console)); 10 engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)"); 11 12 // expose a host object 13 engine.AddHostObject("random", new Random()); 14 engine.Execute("Console.WriteLine(random.NextDouble())"); 15 16 // expose entire assemblies 17 engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core")); 18 engine.Execute("Console.WriteLine(lib.System.DateTime.Now)"); 19 20 // create a host object from script 21 engine.Execute(@" 22 birthday = new lib.System.DateTime(2007, 5, 22); 23 Console.WriteLine(birthday.ToLongDateString()); 24 "); 25 26 // use a generic class from script 27 engine.Execute(@" 28 Dictionary = lib.System.Collections.Generic.Dictionary; 29 dict = new Dictionary(lib.System.String, lib.System.Int32); 30 dict.Add('foo', 123); 31 "); 32 33 // call a host method with an output parameter 34 engine.AddHostObject("host", new HostFunctions()); 35 engine.Execute(@" 36 intVar = host.newVar(lib.System.Int32); 37 found = dict.TryGetValue('foo', intVar.out); 38 Console.WriteLine('{0} {1}', found, intVar); 39 "); 40 41 // create and populate a host array 42 engine.Execute(@" 43 numbers = host.newArr(lib.System.Int32, 20); 44 for (var i = 0; i < numbers.Length; i++) { numbers[i] = i; } 45 Console.WriteLine(lib.System.String.Join(', ', numbers)); 46 "); 47 48 // create a script delegate 49 engine.Execute(@" 50 Filter = lib.System.Func(lib.System.Int32, lib.System.Boolean); 51 oddFilter = new Filter(function(value) { 52 return (value & 1) ? true : false; 53 }); 54 "); 55 56 // use LINQ from script 57 engine.Execute(@" 58 oddNumbers = numbers.Where(oddFilter); 59 Console.WriteLine(lib.System.String.Join(', ', oddNumbers)); 60 "); 61 62 // use a dynamic host object 63 engine.Execute(@" 64 expando = new lib.System.Dynamic.ExpandoObject(); 65 expando.foo = 123; 66 expando.bar = 'qux'; 67 delete expando.foo; 68 "); 69 70 // call a script function 71 engine.Execute("function print(x) { Console.WriteLine(x); }"); 72 engine.Script.print(DateTime.Now.DayOfWeek); 73 74 // examine a script object 75 engine.Execute("person = { name: 'Fred', age: 5 }"); 76 Console.WriteLine(engine.Script.person.name); 77 }