VB.NET:在运行时将类事件添加到接口事件

时间:2013-04-03 18:40:20

标签: delegates event-handling c#-to-vb.net

我在将一个例子从C#转换为VB.NET时遇到了问题。

C#示例具有以下结构。 首先是公共代表。

public delegate void CustomEventHandler(object sender , EventArgs e);

此委托连接到接口事件。

public interface ICustom {
    event CustomEventHandler MyEvent;
}

最后,我得到了一个与委托有关的事件的课程。此外,还有一个以接口为参数的函数。

public class Test {
    public event CustomEventHandler OnEvent;

    public void MySub(ICustom custom) {
        custom.MyEvent += OnEvent;
    }
}

我可以转换此代码,除了将类事件添加到参数的事件中。我的VB.NET代码如下所示:

Public Delegate Sub CustomEventHandler(ByVal sender As Object, ByVal e As EventArgs)

Public Interface ICustom

    Event MyEvent As CustomEventHandler
End Interface

Public Class Test

    Public Event OnEvent As CustomEventHandler

    Public Sub MySub(ByVal custom As ICustom)
        ... How can I add here the event OnEvent to the event custom.MyEvent? ...
    End Sub
End Class

是否可以转换它或是否有其他必要的方法。 感谢您的回复。

1 个答案:

答案 0 :(得分:0)

Event关键字的VB.NET版本具有更严格的规则,您无法访问底层委托对象。您需要编写自定义事件,以便:

Private BackingField As CustomEventHandler

Public Custom Event OnEvent As CustomEventHandler
    AddHandler(ByVal value As CustomEventHandler)
        BackingField = DirectCast(CustomEventHandler.Combine(BackingField, value), CustomEventHandler)
    End AddHandler

    RemoveHandler(ByVal value As CustomEventHandler)
        BackingField = DirectCast(CustomEventHandler.Remove(BackingField, value), CustomEventHandler)
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
        BackingField.Invoke(sender, e)
    End RaiseEvent
End Event

现在你可以实现MySub:

Public Sub MySub(ByVal custom As ICustom)
    AddHandler custom.MyEvent, BackingField
End Sub

请注意,这是自定义事件的非线程安全版本,如果事件可以在另一个线程中取消/订阅,则需要使用SyncLock使其成为线程安全。