How do I create a C# event handler that can be handled in IronPython?

折月煮酒 提交于 2019-12-19 10:27:19

问题


How do I create a C# event handler that can be handled in IronPython?

Note that I am using IronPython 2.0.1. I am able to handle events from system classes with no problems (eg Window.KeyDown) but when I try to define my own C# event an exception is raised when I attempt to hook it from IronPython.

The exception thrown is ArgumentTypeException and it has the message "cannot add to private event". The message seems odd considering the event I am trying to hook is public.

My C# class looks like this:

class Foo
{
    ...

    public event EventHandler Bar;
}

My IronPython setup code looks like this:

ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();
ScriptSource source = engine.CreateScriptSourceFromFile("Test.py");
Foo bar = new Foo();
scope.SetVariable("Foo", bar);
source.Execute(scope); <-- Exception is thrown here.

My IronPython script looks like this:

def BarHandler(*args):
    pass

Foo.Bar += BarHandler

Does anyone know if I am doing this wrong?

Or is something wrong with IronPython?


回答1:


I figured it out.

The class needs to be public as well as the event.

eg

public class Foo
{
   ...   

    public event EventHandler Bar;
}


来源:https://stackoverflow.com/questions/1079265/how-do-i-create-a-c-sharp-event-handler-that-can-be-handled-in-ironpython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!