在IronPython中访问C#类成员

时间:2022-09-02 12:06:01

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#代码中,我有一个类,它存储了一些我希望传递给List中的python代码的数据。但是,当我尝试在我的python代码中访问该类的属性时,我得到MissingMemberException。这里有一些示例代码来显示我的意思:

C#:

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

The MissingMemberException says "Event contains no member named EventId"

MissingMemberException表示“事件不包含名为EventId的成员”

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,包括List 和List 等基本类型的列表,它们工作正常。

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

那么如何在我的python脚本中访问这些类属性,EventId和EventName?

1 个解决方案

#1


14  

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.

尝试将Event类设为public。问题可能是虽然属性是公共的,但默认情况下类型是内部的,因此动态类型不会“看到”任何仅由该类型声明的成员。

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.

这只是一个猜测,如果它是错的,请说出来我可以删除答案,避免将来混淆任何人。通过在C#中的另一个程序集中动态键入,在一个程序集中使用匿名类型可以获得相同的效果。

#1


14  

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.

尝试将Event类设为public。问题可能是虽然属性是公共的,但默认情况下类型是内部的,因此动态类型不会“看到”任何仅由该类型声明的成员。

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.

这只是一个猜测,如果它是错的,请说出来我可以删除答案,避免将来混淆任何人。通过在C#中的另一个程序集中动态键入,在一个程序集中使用匿名类型可以获得相同的效果。