使用类名作为字符串

时间:2016-06-09 09:35:49

标签: c# .net ironpython cross-language

This所以问题提供了在C#中创建python类实例的代码。

以下代码强制事先知道python函数名。但是我需要指定要由字符串执行的类名和函数名。

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);

dynamic class_object = scope.GetVariable("Calculator");
dynamic class_instance = class_object();
int result = class_instance.add(4, 5);  // I need to call the function by a string

2 个答案:

答案 0 :(得分:2)

最简单的方法是安装名为Dynamitey的nuget包。它专门用于在动态对象上调用动态方法(以及执行其他有用的操作)。安装后,只需执行:

static void Main(string[] args)
{
    ScriptEngine engine = Python.CreateEngine();
    ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
    ScriptScope scope = engine.CreateScope();
    source.Execute(scope);

    dynamic class_object = scope.GetVariable("Calculator");
    dynamic class_instance = class_object();
    int result = Dynamic.InvokeMember(class_instance, "add", 4, 5);
}

如果你想知道它在底层做了什么 - 它使用与C#编译器用于动态调用的相同代码。这是一个很长的故事,但如果你想了解这一点,你可以这样做here

答案 1 :(得分:0)

您正在寻找Invoke和InvokeMember IronPython方法:

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);

object class_object = scope.GetVariable("Calculator");
object class_instance = engine.Operations.Invoke(class_object);
object[] args = new object[2];
args[0] = 4;
args[1] = 5;
int result = (int)engine.Operations.InvokeMember(class_instance, "add", args);  // Method called by string
                                                                                //  "args" is optional for methods which don't require arguments.

我也将dynamic类型更改为object,因为此代码示例不再需要它,但是如果需要调用一些固定名称,则可以保留它方法。