C#,IronPython-从非静态类导入(?)
本文关键字:导入 静态类 IronPython- | 更新日期: 2023-09-27 18:22:26
我有一个带有一些实例方法的非静态C#类,我需要从IronPython脚本中调用这些方法。目前我是这样做的:
scope.SetVariable("class", instanceOfClass);
在C#代码和中
class.SomeMethod(args)
在脚本中。
我想要的是能够调用此类方法,而无需每次在脚本中添加class.
。每个脚本都有自己的类实例,并且在一个脚本中只使用一个实例。
如果这个类是静态的,那么解决方案将是from ClassName import *
,但据我所知,对于非静态类没有类似的构造。
如何做到这一点?我有一些想法(比如使用反射,或者以编程方式将class.
添加到Python源代码中的每个调用中),但它们过于复杂,甚至可能无法实现。
UPD:
使用这样的python代码解决的问题(在实际脚本之前):
def Method1(arg1): # for simple method
class.Method1(arg1)
def Method2(arg = 123): # for default values
class.Method2(arg)
def Method3(*args): # for params
class.Method3(args)
# so on
from ClassName import *
实际上是from namespace import type
。此语句使该类型可以通过Python中的类型名称使用。类是否是静态的没有区别。将此示例代码Environment视为静态类。
import clr
from System import Environment
print Environment.CurrentDirectory
要解决问题,请将类函数的委托注入ScriptScope,而不是类本身。
样品类别
public class Foo {
public string GetMyString(string input) {
return input;
}
}
使用
private static void Main(string[] args) {
ScriptEngine engine = Python.CreateEngine();
string script = "x = GetMyString('value')";
Foo foo = new Foo();
ScriptSource scriptSource = engine.CreateScriptSourceFromString(script);
ScriptScope scope = engine.CreateScope();
scope.SetVariable("GetMyString", new Func<string, string>(foo.GetMyString));
scriptSource.Execute(scope);
string output = scope.GetVariable<string>("x");
Console.WriteLine(output);
}
打印
值