IronPython call method by name

不打扰是莪最后的温柔 提交于 2019-12-11 11:16:47

问题


Is there any way to call method by name and specify arguments without using dynamic? (C#)

UPDATE:

` public class Program { public static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope();

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

        dynamic calculator = scope.GetVariable("Calculator");
        dynamic calculatorInstance = engine.Operations.CreateInstance(calculator);
        dynamic result = engine.Operations.InvokeMember(calculatorInstance, "sample");

        Console.ReadKey();
    }
}

`

class Calculator: def sample(self): return 'test'

That works great


回答1:


You can use the ObjectOperations class to perform dynamic operations, and you can get an instance of it from a ScriptEngine instance:

ScriptEngine engine = ...;
object result = engine.Operations.InvokeMember(o, "foo", 1, 2, "3");



回答2:


Open Source Impromptu-Interface (can be found in nuget) has a bunch of methods for doing reflection-like invocation on any dynamic object, python, ruby, c#, etc, as it uses the dlr c# binder code.

 Impromptu.InvokeMember(o, "foo", 1, 2, "3")

But in this case, JeffHardy's answer is best, since you are already working with a script engine.



来源:https://stackoverflow.com/questions/8970458/ironpython-call-method-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!