在 VB.NET 中添加事件处理程序的语法 [英] Syntax for adding an event handler in VB.NET

查看:28
本文介绍了在 VB.NET 中添加事件处理程序的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码需要转换为 VB.NET.问题是我发现的每个翻译工具都错误地转换了添加处理程序部分.我一个人好像做不到.

I have following code i need to convert to VB.NET. Problem is every translation tool I found is converting the add handler part wrong. I don't seem to be able to do it by myself.

FtpClient ftpClient = new FtpClient();
ftpClient.UploadProgressChanged += new EventHandler<UploadProgressChangedLibArgs>(ftpClient_UploadProgressChanged);
ftpClient.UploadFileCompleted += new EventHandler<UploadFileCompletedEventLibArgs>(ftpClient_UploadFileCompleted);

推荐答案

在 VB.NET 中有两种不同的方法可以将事件处理程序方法与事件相关联.

There are two different ways to associate event handler methods with an event in VB.NET.

第一个涉及使用 Handles 关键字,您将其附加到事件处理程序方法定义的末尾.例如:

The first involves the use of the Handles keyword, which you append to the end of the event handler method's definition. For example:

Sub ftpClient_UploadProgressChanged(sender As Object, e As UploadProgressChangedLibArgs) Handles ftpClient.UploadProgressChanged
    ' ...
End Sub

Sub ftpClient_UploadFileCompleted(sender As Object, e As UploadFileCompletedEventLibArgs) Handles ftpClient.UploadFileCompleted
    ' ...
End Sub

如果您已经有单独定义的事件处理程序方法(即,如果您没有使用 lambda 语法),则第一种方法要简单得多.我会尽可能推荐它.

The first method is much simpler if you've already got separately defined event handler methods anyway (i.e., if you're not using a lambda syntax). I would recommend it whenever possible.

第二个涉及显式使用AddHandler 语句,就像C# 中的+=.如果您想动态关联事件处理程序,则需要使用它,例如如果您需要在运行时更改它们.所以你的代码,从字面上转换,看起来像这样:

The second involves the explicit use of the AddHandler statement, just like += in C#. This is the one you need to use if you want to associate event handlers dynamically, e.g. if you need to change them at run time. So your code, literally converted, would look like this:

Dim ftpClient As New FtpClient()
AddHandler ftpClient.UploadProgressChanged, AddressOf ftpClient_UploadProgressChanged
AddHandler ftpClient.UploadFileCompleted, AddressOf ftpClient_UploadFileCompleted

如您所说,我尝试通过 Developer Fusion 的转换器运行您的代码 并惊讶地发现他们返回了无效的 VB.NET 代码:

Like you said, I tried running your code through Developer Fusion's converter and was surprised to see that they were returning invalid VB.NET code:

' WRONG CODE!
Dim ftpClient As New FtpClient()
ftpClient.UploadProgressChanged += New EventHandler(Of UploadProgressChangedLibArgs)(ftpClient_UploadProgressChanged)
ftpClient.UploadFileCompleted += New EventHandler(Of UploadFileCompletedEventLibArgs)(ftpClient_UploadFileCompleted)

事实证明,这是一个一个已知错误可能值得投票!

Turns out, that's a known bug that might be worth voting for!

这篇关于在 VB.NET 中添加事件处理程序的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆