从IronPython脚本访问主机类

| 如何从IronPython脚本访问C#类? C#:
public class MyClass
{
}

public enum MyEnum
{
    One, Two
}

var engine = Python.CreateEngine(options);
var scope = engine.CreateScope();
scope.SetVariable(\"t\", new MyClass());
var src = engine.CreateScriptSourceFromFile(...);
src.Execute(scope);
IronPython脚本:
class_name = type(t).__name__     # MyClass
class_module = type(t).__module__ # __builtin__

# So this supposed to work ...
mc = MyClass() # ???
me = MyEnum.One # ???

# ... but it doesn\'t
更新 我需要导入在托管程序集中定义的类。     
已邀请:
        您已经将
t
设置为
MyClass
的实例,但是您试图将其用作类本身。 您需要从IronPython脚本中导入ѭ3,或注入某种工厂方法(由于类不是C#中的一流对象,因此您不能直接传入ѭ3)。另外,您可以传入
typeof(MyClass)
,然后使用
System.Activator.CreateInstance(theMyClassTypeObject)
来建立实例。 由于您还需要访问
MyEnum
(请注意,您正在脚本中使用它,而没有引用它可能来自何处),因此我建议仅使用导入:
import clr
clr.AddReference(\'YourAssemblyName\')

from YourAssemblyName.WhateverNamespace import MyClass, MyEnum

# Now these should work, since the objects have been properly imported
mc = MyClass()
me = MyEnum.One
您可能需要尝试使用脚本源类型(我认为
File
效果最好)和脚本执行路径来获得
clr.AddReference()
调用才能成功。     

要回复问题请先登录注册