无法从C#访问IronPython类的属性

时间:2016-08-27 20:06:47

标签: c# python dynamic ironpython scriptengine

我有一些C#代码实例化IronPython类并从中运行一些代码。有问题的IronPython类实现了一个在C#中定义的接口。它还定义了一些自己的属性。

我无法访问由类本身定义的属性,我想知道是否有人知道如何执行此操作?

以下是IronPython类的示例:

import clr
clr.AddReference('System.Core')
from System import Tuple

class TestClass (ITestInterface):
    ExamplePropertyOne = System.Tuple[System.String, System.String]("Hello", "World!")

    def ExampleMethod(self, some_parameter):
        ...code...

我创建一个ScriptEngine对象来使用IronPython类,如下所示:

Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
var python_script_engine = Python.CreateEngine(options);
var python_script_scope = python_script_engine.CreateScope();
python_script_engine.ExecuteFile("my_python_class.py", python_script_scope);

//The class could have any name, so instead of requesting the class by name,
//I simply iterate through the items in the python file to find the items
//that implements the expected interface, like so:
var python_script_items = python_script_scope.GetItems();
python_script_items = python_script_items.Where(x => x.Value is IronPython.Runtime.Types.PythonType);

foreach (var item in python_script_items)
{
    System.Type item_type = (Type)item.Value;
    var implemented_interfaces = item_type.GetInterfaces();
    if (implemented_interfaces != null && implemented_interfaces.Length > 0)
    {
        if (implemented_interfaces.ToList().Contains(typeof(ITestInterface)))
        {
            var class_to_instantiate = item.Value;
            var class_instance = class_to_instantiate();

            ...code here to get properties of class...
        }
    }
}

就像FYI一样,在foreach循环中,“item”是KeyValuePair(字符串是键,动态对象是值)。在迭代了很多项之后,当我们到达键是“TestClass”的正确键值对时,if语句成功(我已经逐步完成代码以确保if语句在正确的项目上成功)

不幸的是,虽然我们输入带有“TestClass”的if语句作为项的键,但是当我实例化该类时,我似乎无法查看在TestClass上声明的属性。我只能看到从ITestInterface实现的方法。

我已经尝试了以下内容,不知道哪个会得到正确的结果:

var list1 = Dynamic.GetMemberNames(class_instance);  //Using Dinamitey
var list2 = python_script_engine.Operations.GetMemberNames(class_instance);
var fields = item_type.GetFields();
var properties = item_type.GetProperties();
var attributes = item_type.CustomAttributes;
var attributes2 = item_type.GetCustomAttributes(false);
var members = item_type.GetMembers();
var var_names = python_script_scope.GetVariableNames();

以上都不会在结果中返回属性“ExamplePropertyOne”,它是“TestClass”的成员。我只能看到实现的方法。当然,python_script_scope.GetVariableNames只返回实例化类之外的范围内的信息。

那么,有什么建议吗?为什么我只能看到界面成员?如何访问班级的属性?

感谢您的帮助!

0 个答案:

没有答案