隨著web2.0和敏捷開發方法論的興起,動態語言的靈活高效的特性成為了它被更多項目選擇和使用的理由。一些大型網站已開始使用動態語言來實現。微軟更是不甘落後,建立了dlr(動態語言運行時)來吸引動態語言愛好者在其上實現動態語言。ironpython就是其主要成員之一。
// 定義一個業務對象
class businessobject
{
private string oneproperty;
public string oneproperty
{
get { return oneproperty; }
set { oneproperty = value; }
}
public void onemethod(string val)
{
// do something...
}
}
// 取得當前的engine
scriptengine engine = pythonengine.currentengine;
// 取得scope
scriptscope scope = engine.createscope();
businessobject bo = new businessobject();
bo.oneproperty = 10;
// 設定變數,這是互動的關鍵!
scope.setvariable("bo", bo);
// 這是要招待的指令碼, bo即從宿主傳遞過來的對象
string code = "bo.oneproperty = '中文'/n";
code += "bo.onemethod('參數')";
// 建立scriptsource
scriptsource source = engine.createscriptsourcefromstring(code, sourcecodekind.statements);
// 執行指令碼
source.execute(scope);
可以預見,通過這個互動的方式,可以將一些邏輯代碼從宿主環境中剝離出來,
改由ironpython進行處理,這樣可以增強系統的靈活性。