1

我在将示例从 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

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

4

1 回答 1

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 使其线程安全。

于 2013-04-03T19:13:09.280 回答