我曾經使用過這種方法,既節省了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一堆更完整的樣本。
那真是太棒了!謝謝! – Schotime 2010-08-10 04:50:34
對於NoRM的貢獻者來說,這是我所能做的至少... – 2010-08-10 13:17:45