在IronPython中访问C#类成员 [英] Accessing C# class members in IronPython

查看:43
本文介绍了在IronPython中访问C#类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#代码中,我有一个类,该类存储一些我想传递给List中的python代码的数据.但是,当我尝试在python代码中访问该类的属性时,得到MissingMemberException.这里有一些示例代码来说明我的意思:

In my C# code I have a class which stores some data I wish to pass down to my python code in a List. However, when I try to access properties of that class inside my python code I get MissingMemberException. Here some example code to show what I mean:

C#:

class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
} 

//other processing here...

//this just fills the list with event objects
List<Event> eventList = GetEvents(); 

//this sets a variable in the ScriptScope 
PythonEngine.SetVariable( "events", eventList);

PythonEngine.Execute("eventParser.py");

eventParser.py:

eventParser.py:

for e in events:
    print e.EventId, " / ", e.EventName

MissingMemberException说事件不包含名为EventId的成员"

The MissingMemberException says "Event contains no member named EventId"

我已经测试过将其他类型传递给python,包括诸如List< int >List< string >的原始类型的列表,并且它们可以正常工作.

I have tested passing other types to the python, including lists of primitive types like List< int > and List< string > and they work fine.

那么如何在我的python脚本中访问这些类属性EventIdEventName?

So how do I access these class properties, EventId and EventName in my python script?

推荐答案

尝试将Event类公开.问题可能是,尽管属性是公共的,但默认情况下 type internal,因此动态类型不会看到"任何成员只能通过该类型声明.

Try making the Event class public. The problem may be that although the property is public, the type is internal by default, and so the dynamic typing doesn't "see" any of the members which are only declared by that type.

这只是一个猜测,如果有误,请说出答案,以便我删除答案并避免将来使任何人感到困惑.通过在C#中动态键入另一个程序集,在一个程序集中使用匿名类型,您确实会获得相同的效果.

It's just a guess, and if it's wrong, please say so I can delete the answer and avoid confusing anyone in the future. You do get the same effect from using anonymous types in one assembly via dynamic typing in another assembly just within C# though.

这篇关于在IronPython中访问C#类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆