使用类名作为字符串将python类实例化为C#
所以问题提供了在C#中创建python类实例的代码 下面的代码强制提前知道python函数名。但是,我需要指定要通过字符串执行的类名和函数名使用类名作为字符串将python类实例化为C#,c#,.net,ironpython,cross-language,C#,.net,Ironpython,Cross Language,所以问题提供了在C#中创建python类实例的代码 下面的代码强制提前知道python函数名。但是,我需要指定要通过字符串执行的类名和函数名 ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py"); ScriptScope scope = engine.CreateScope(); source.Execute(sco
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
最简单的方法是安装名为
dynametiy
的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#编译器用于动态调用的代码相同。这是一个很长的故事,但是如果您想了解这一点,您可以这样做。您正在寻找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.
我还将动态
类型更改为对象
,因为对于这个代码示例,您不再需要它,但是如果您需要调用一些固定名称方法,您可以自由保留它