代码之家  ›  专栏  ›  技术社区  ›  Schotime

使用IronRuby或IronPython修改C对象列表

  •  2
  • Schotime  · 技术社区  · 16 年前

    如果我有一个物品清单。 List<Foo> 哪里 Foo 有几个属性,然后我可以创建一个或多个为每行运行的ironruby或ironpython脚本。

    下面是一些伪代码:

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

    我需要一个动态的方式来修改代码存储在数据库或文件中的列表。

    如果您认为有更好的方法可以做到这一点,或者有其他方法可以为客户机编写自定义例程,从数据库中提取特定于客户机的数据(导出),请发表评论或留下建议。

    1 回复  |  直到 16 年前
        1
  •  4
  •   John Zablocki    16 年前

    我以前使用过这种方法,既可以将IronPython脚本保存在数据库中,也可以保存在文件中。我喜欢的模式是用约定的名称存储Python函数。换句话说,如果您正在处理Foo类型的对象,那么在.py文件或表中可能有一个名为“Foo\u filter”的Python函数。最终,您可以执行一个Python文件并将函数解析到函数引用的字典中。

    你的foo课程:

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

    设置Foo并调用getPythonFunc(i);

    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()
    

    基于属性应用规则的简单方法(不是在Foo上添加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

    推荐文章