如何创建可在IronPython中处理的C#事件处理程序?

时间:2021-08-22 06:29:59

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

如何创建可在IronPython中处理的C#事件处理程序?

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.

请注意,我使用的是IronPython 2.0.1。我能够毫无问题地处理来自系统类的事件(例如Window.KeyDown)但是当我尝试定义自己的C#事件时,当我尝试从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.

抛出的异常是ArgumentTypeException,它有消息“无法添加到私有事件”。考虑到我试图挂钩的事件是公开的,这条消息似乎很奇怪。

My C# class looks like this:

我的C#类看起来像这样:

class Foo
{
    ...

    public event EventHandler Bar;
}

My IronPython setup code looks like this:

我的IronPython设置代码如下所示:

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:

我的IronPython脚本如下所示:

def BarHandler(*args):
    pass

Foo.Bar += BarHandler

Does anyone know if I am doing this wrong?

有谁知道我做错了吗?

Or is something wrong with IronPython?

或者IronPython出了什么问题?

1 个解决方案

#1


3  

I figured it out.

我想到了。

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

课程需要公开以及活动。

eg

例如

public class Foo
{
   ...   

    public event EventHandler Bar;
}

#1


3  

I figured it out.

我想到了。

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

课程需要公开以及活动。

eg

例如

public class Foo
{
   ...   

    public event EventHandler Bar;
}