2016-06-09 29 views
2

this SO问题提供了用于在C#中创建python类的实例的代码。使用类名称将python类实例化为C#使用类名作为字符串

以下代码强制提前知道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

最简单方法是安装NuGet包称为Dynamitey。它专门设计用于在动态对象上调用动态方法(并执行其他有用的事情)。你安装它后,只是做:

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例如。

相关问题