話說最近有特別的需求,要用C#調用一種動態的語言執行一些經常改變的操作。由於我對Lua情有獨鍾,所以一開始就想到了它,了解了下LuaInterface,貌似問題挺多(issue list上有許多沒有解決的defect),而且好像與時下很火的DLR沒什么關系。
MS支持的Iron系語言看起來比較牛的樣子,不過Python和Ruby我都沒有接觸過,最近也沒有學門新語言的時間。搜了下IronLua,Google上有工程卻沒有代碼。由於本人經常用JS寫一些WSH的腳本(CMD太爛了),所以對JS還挺熟,於是IronJS就這樣被我找到了!!
IronJS功能是非常地牛,但文檔確實是少了點,除了項目wiki和blog上有一點,基本上就很難找到了,中文的更少了。剛試了下,感覺很好,記錄下來,拋磚引玉,希望能引起大家的興趣。
准備工作
從github上下載編譯好的dll或者把源代碼下下來編譯下,獲得IronJS.dll,添加引用。
Hello IronJS
1 static void Main(string[] args) 2 { 3 var ctx = new IronJS.Hosting.CSharp.Context(); 4 dynamic hello = ctx.Execute("(function (){ return {msg:'你好,IronJS'};})();"); 5 Console.Out.WriteLine(hello.msg); 6 Console.Out.WriteLine(hello.noexist); 7 Console.ReadKey(true); 8 }
這段代碼一看就懂,先是新建一個js運行的context,然后執行一js的函數,這個js的函數返回一個object,包含msg屬性,利用.NET 4.0的dynamic關鍵字,我們可以很方便地引用成員,另外也可以看到當引用不存在的成員時會返回undefined,符合期望。
Access C# object
1 class User 2 { 3 public string Name { get; set; } 4 } 5 6 static void Main(string[] args) 7 { 8 var ctx = new IronJS.Hosting.CSharp.Context(); 9 var user = new User() { Name = "張三" }; 10 ctx.SetGlobal("user", user); 11 ctx.CreatePrintFunction(); 12 ctx.Execute(@" 13 print(user.Name); 14 print(user.noexist); 15 print(typeof user.nodef == 'undefined' ? 'Yes' : 'No')"); 16 Console.ReadKey(true); 17 }
第10行將user變量設置到js的全局變量中,第11行在js環境中創建了一個print函數,然后用js訪問了user對象屬性,並且在訪問不存在的屬性時,返回的undefined,完全符合期望。
JSON
1 static void Main(string[] args) 2 { 3 var ctx = new IronJS.Hosting.CSharp.Context(); 4 var json = @" 5 var configs = { 6 location:{x:0, y:0}, 7 size:{cx:100, cy:200}, 8 color:'red' 9 };"; 10 11 var configs = ctx.Execute(json); 12 13 Console.Out.WriteLine("x={0},y={1},cx={2},cy={3},color={4}", 14 configs.location.x, 15 configs.location.y, 16 configs.size.cx, 17 configs.size.cy, 18 configs.color); 19 20 Console.ReadKey(true); 21 }
就是這么簡單!如果用戶程序需要一個配置文件,完全沒有必要整XML,就算LINQ to XML簡單,但是能簡單到直接讀上來執行一下嗎。
Regular Expression
因為兩年前據說IronJS不支持正則表達式,所以特意試下,現在真的是支持的!
1 static void Main(string[] args) 2 { 3 var ctx = new IronJS.Hosting.CSharp.Context(); 4 ctx.Execute(@"var re = /(\d+)-(\d+)-(\d+)/;"); 5 dynamic result = ctx.Execute(@"re.exec('2012-11-29');"); 6 Console.Out.WriteLine("{0}年{1}月{2}日", result[1], result[2], result[3]); 7 Console.ReadKey(true); 8 }
睡覺了,上面試的幾點基本能夠滿足我整一個配置文件,然后根據一個內嵌js語句的模板生成一個C文件的需求。有空再研究更多的功能吧。