访问Iron python中的.Net枚举
我正试图访问IronPython中的 .Net(C#)枚举,假设我们有
Test.dll的
// Contains Several Enums enum TestType{..} enum TestQuality{..} .... .... enum TestStatus{..} //Similarly Multiple functions public void StartTest(TestType testType, TestQuality testQuality){..} .... .... public TestStatus GetTestStatus(){..}
现在如果我尝试调用上面的函数,我需要选择适当的枚举参数,到目前为止我所做的是这个,
铁蟒[vs2012]
import clr clr.AddReference('Test.dll') from TestDll import * test = Test() # Initiate Enums enumTestType = TestType enumTestQuality = TestQuality .... .... enumTestStatus = TestStatus #Call Functions test.StartTest(enumTestType.Basic, enumTestQuality.High) .... .... # goes on
现在上面的IronPython代码运行正常,这里唯一奇怪的是我需要在使用函数之前启动所有枚举(Intellisence在这里不起作用),当有更多的枚举使用时,这将变得更加困难。 而在C#环境(vs2012)中我们不必启动,但我们可以在调用函数时立即使用它们。
在IronPython中有更好的方法吗?
如果我错了请纠正我,谢谢!
假设枚举包含在Test
类中,您可以使用它们完全限定
test.StartTest(Test.TestType.Basic, Test.TestQuality.High)
或通过导入
from TestDll.Test import TestQuality, TestType test.StartTest(TestType.Basic, TestQuality.High)
如果枚举与Test
类位于同一名称空间中,则它们应该可以使用而无需其他导入:
test.StartTest(TestType.Basic, TestQuality.High)
我有同样的问题,但我用另一种方式修复它:使用ScriptRuntime.LoadAssembly
。
先决条件:
-
VS2013
-
C#app可执行文件,加上Test.dll程序集。 IronPython由C#app托管。
-
Test.dll :(注意所有都在TestDll命名空间内)
namespace TestDll { // Contains Several Enums enum TestType{..} enum TestQuality{..} .... .... enum TestStatus{..} //Similarly Multiple functions public void StartTest(TestType testType, TestQuality testQuality){..} .... .... public TestStatus GetTestStatus(){..} }
我只是这样创建了IronPython引擎:
eng = Python.CreateEngine(); eng.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(TestType))); // This allows "from TestDLL import *" in Python scripts
然后,用通常的方式执行脚本
string pysrc = ...; // omitted, taken from the python script below ScriptSource source = eng.CreateScriptSourceFromString(pysrc); ScriptScope scope = eng.CreateScope(); source.Execute(scope);
这允许我编写这个Python代码并在C#app中执行它:(注意我直接使用枚举名称)
from TestDll import * test = Test() #Call Functions test.StartTest(TestType.Basic, TestQuality.High) .... .... # goes on