从 C# 库触发事件到 VB Winform 程序

Fire Event from a C# library into a VB Winform program

我是一名 C# 程序员,并制作了一个 C# 库来处理 tcp/ip 聊天。 现在我有必要从 Server VB Winform 程序中使用它。 我很确定这是一个容易解决的问题,但我已经苦苦挣扎了好几天。 所以在 C# 中我有 class:

public class AsynchronousServer
{
    public AsynchronousServer()
    {
    }

    public delegate void ChangedEventHandler(string strMessage);
    public static event ChangedEventHandler OnNotification;
    public static event ChangedEventHandler OnAnswerReceived;
    ...
}

现在我要关注服务器程序了: 如果那个 VB 程序是用 C# 编写的,我会编写下面的代码来通过单击按钮连接服务器

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        AsynchronousServer.OnNotification += AsynchronousServer_OnNotification;
        AsynchronousServer.OnAnswerReceived += AsynchronousServer_OnAnswerReceived;
        AsynchronousServer.StartServer(tbxIpAddress.Text,tbxPort.Text);
    }

VB中的相同程序:

Imports SocketLibrary

    Public Class Form1
    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        AsynchronousServer.OnNotification                       <--- member not present
        AsynchronousServer.OnAnswerReceived                     <--- member not present
        AsynchronousServer.StartServer(tbxIpAddress.Text, tbxPort.Text);<-----OK
    End Sub
End Class

问题是成员 AsynchronousServer.OnNotification 根本不存在,所以我无法添加活动。 我知道我可能必须添加 WithEvents 关键字,但尽管我尝试了但我无法成功。

简而言之,我必须将那个 VB winform 程序连接到一个 C# 库事件,我无法从我的 VB class.

中看到它

感谢您的帮助

帕特里克

Visual Basic 有 AddHandlerRemoveHandler,当左边的项目是 event.

但是,您也可以选择将某些字段(因此,与 class 实例上的实例事件更相关)声明为 WithEvents1. Whenever you assign a reference to a WithEvents field, it will automagically remove previous event handlers it installed on the old instance and then install new handlers on the new instance. This works in concert with the Handles 子句,指示应连接哪些事件处理方法。这使您可以采用更 "declarative" 的方法来处理事件。但它不适用于 static 事件。

(另外请注意,当然通常很容易从 VB 代码中消耗 C# 事件 - 因为 WinForms 等是用 C# 实现的,但可用于两种语言)


1我在这里提到它并不是因为我一定要推荐它,而是因为你会遇到相当多的 VB.NET 使用这种形式的代码,包括 form-designer生成的代码。在 .NET 之前的 VB 中,它是 连接事件处理程序的方式。

我假设你从未使用过 VB 因此会回答你:
您需要使用 AddHandler:

AddHandler AsynchronousServer.OnNotification, AddressOf YourMethod

顺便说一句,恕我直言,静态事件非常糟糕。