我想从 C# 创建 IronPython 类的实例,但我目前的尝试似乎都失败了。
这是我当前的代码:
ConstructorInfo[] ci = type.GetConstructors();
foreach (ConstructorInfo t in from t in ci
where t.GetParameters().Length == 1
select t)
{
PythonType pytype = DynamicHelpers.GetPythonTypeFromType(type);
object[] consparams = new object[1];
consparams[0] = pytype;
_objects[type] = t.Invoke(consparams);
pytype.__init__(_objects[type]);
break;
}
我可以通过调用 t.Invoke(consparams) 来获取创建的对象实例,但__init__
似乎没有调用该方法,因此我从 Python 脚本中设置的所有属性都没有使用。即使使用显式pytype.__init__
调用,构造的对象似乎仍然没有被初始化。
使用 ScriptEngine.Operations.CreateInstance 似乎也不起作用。
我将 .NET 4.0 与 IronPython 2.6 一起用于 .NET 4.0。
编辑:关于我打算如何做到这一点的小说明:
在 C# 中,我有一个类如下:
public static class Foo
{
public static object Instantiate(Type type)
{
// do the instantiation here
}
}
在 Python 中,以下代码:
class MyClass(object):
def __init__(self):
print "this should be called"
Foo.Instantiate(MyClass)
该__init__
方法似乎从未被调用。