在 VB.NET 中添加事件处理程序的语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17511140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Syntax for adding an event handler in VB.NET
提问by sharkyenergy
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.
我有以下代码需要转换为 VB.NET。问题是我发现的每个翻译工具都错误地转换了添加处理程序部分。我一个人好像做不到。
FtpClient ftpClient = new FtpClient();
ftpClient.UploadProgressChanged += new EventHandler<UploadProgressChangedLibArgs>(ftpClient_UploadProgressChanged);
ftpClient.UploadFileCompleted += new EventHandler<UploadFileCompletedEventLibArgs>(ftpClient_UploadFileCompleted);
回答by Cody Gray
There are two different ways to associate event handler methods with an event in VB.NET.
有两种不同的方法可以将事件处理程序方法与 VB.NET 中的事件相关联。
The first involves the use of the Handleskeyword, which you append to the end of the event handler method's definition. For example:
第一个涉及Handles关键字的使用,您将其附加到事件处理程序方法定义的末尾。例如:
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
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.
如果您已经有单独定义的事件处理程序方法(即,如果您没有使用 lambda 语法),则第一种方法要简单得多。我会尽可能推荐它。
The second involves the explicit use of the AddHandlerstatement, 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:
第二个涉及AddHandler语句的显式使用,就像+=在 C# 中一样。如果您想动态关联事件处理程序(例如,如果您需要在运行时更改它们),则需要使用此方法。所以你的代码,字面上转换,看起来像这样:
Dim ftpClient As New FtpClient()
AddHandler ftpClient.UploadProgressChanged, AddressOf ftpClient_UploadProgressChanged
AddHandler ftpClient.UploadFileCompleted, AddressOf ftpClient_UploadFileCompleted
Like you said, I tried running your code through Developer Fusion's converterand was surprised to see that they were returning invalid VB.NET code:
就像你说的,我尝试通过Developer Fusion 的转换器运行你的代码,并惊讶地发现他们返回了无效的 VB.NET 代码:
' 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 bugthat might be worth voting for!

