2010-08-09 33 views
2

如果我有一個對象列表,例如。 List<Foo>其中Foo有幾個屬性,然後我可以創建一個或多個Ironruby或Ironpython腳本來運行每行。使用IronRuby或IronPython修改C#對象列表

下面是一些僞代碼:

var items = new List<Foo>(); 
foreach(var item in items) { 
    var pythonfunc = getPythonFunc("edititem.py"); 
    item = pythonfunc(item); 
} 

我需要一個動態的方式來修改其中的代碼存儲在一個數據庫或文件列表。

如果您認爲有更好的方法來做到這一點,或者有一個替代方案,以便可以爲可以從數據庫(導出)中提取客戶端特定數據的客戶端編寫自定義例程,請評論或留下建議。

感謝

回答

4

我曾經使用過這種方法,既節省了IronPython的腳本,在數據庫和文件。我喜歡的模式是用常規名稱存儲Python函數。換句話說,如果您正在處理Foo類型的對象,那麼您的.py文件或表中可能有一個名爲「foo_filter」的Python函數。最終,您可以執行一個Python文件,並將這些函數解析爲函數引用的字典。

一個快速的示例應用程序...

你的Foo類:

public class Foo { 
    public string Bar { get; set; } 
} 

設置Foo和調用getPythonFunc(我);

var items = new List<Foo>() { 
    new Foo() { Bar = "connecticut" }, 
    new Foo() { Bar = "new york" }, 
    new Foo() { Bar = "new jersey" }      
}; 

items.ForEach((i) => { getPythonFunc(i); Console.WriteLine(i.Bar); }); 

一個快速和骯髒的getPythonFun實施...的ScriptXXX對象圖顯然應緩存方式,應由檢索的getVariable變量()。

static void getPythonFunc(Foo foo) { 

    ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration(); 
    ScriptRuntime runtime = new ScriptRuntime(setup); 
    runtime.LoadAssembly(Assembly.GetExecutingAssembly()); 
    ScriptEngine engine = runtime.GetEngine("IronPython"); 
    ScriptScope scope = engine.CreateScope(); 

    engine.ExecuteFile("filter.py", scope); 

    var filterFunc = scope.GetVariable("filter_item"); 
    scope.Engine.Operations.Invoke(filterFunc, foo); 
} 

filter.py的內容:

def filter_item(item): 
    item.Bar = item.Bar.title() 

一個簡單的方法來應用基於屬性(不添加對富Size屬性的)規則:

var items = new List<Foo>() { 
    new Foo() { Bar = "connecticut", Size = "Small" }, 
    new Foo() { Bar = "new york", Size = "Large" }, 
    new Foo() { Bar = "new jersey", Size = "Medium" } 
}; 

更改getPythonFun()中調用ScriptScope的GetVariable()的行:

var filterFunc = scope.GetVariable("filter_" + foo.Size.ToLower()); 

而且filter.py

def filter_small(item): 
    item.Bar = item.Bar.lower() 

def filter_medium(item): 
    item.Bar = item.Bar.title() 

def filter_large(item): 
    item.Bar = item.Bar.upper() 

的新內容,我可以在http://www.codevoyeur.com/Articles/Tags/ironpython.aspx一堆更完整的樣本。

+0

那真是太棒了!謝謝! – Schotime 2010-08-10 04:50:34

+0

對於NoRM的貢獻者來說,這是我所能做的至少... – 2010-08-10 13:17:45