如何写事件处理程序在VB.NET?如何写、事件、程序、NET

2023-09-06 17:11:57 作者:人不丑嘴还甜长得帅还有钱

我想测试一下很简单的事件处理在VB.NET。

I am trying to test out very simple event handling in VB.NET.

到目前为止,我有:

Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate

Sub MySub
    Raise TestEvent
End Sub

你怎么会写的事件处理程序,只是显示一个简单的的MessageBox 上面的事件?

推荐答案

写的处理方法很简单 - 只写了小组它不带任何参数,并显示一个消息框

Writing the handler method is simple - just write a Sub which takes no parameters and displays a message box.

您再需要订阅的处理程序的情况下,你可以做任何添加的 手柄 子句的方法:

You then need to subscribe the handler to the event, which you can either do adding a Handles clause to the method:

Sub ShowMessageBox() Handles foo.TestEvent

或使用 的AddHandler 语句:

AddHandler foo.TestEvent, AddressOf ShowMessageBox

请注意,要遵循.NET约定,您的代理应该有两个参数 - 类型的一个对象来指定对象引发事件,并键入一个 EventArgs的或子类,提供任何额外的信息。这不是的需要的由语言,但它是一个广泛的,其次约定。

Note that to follow .NET conventions, your delegate should have two parameters - one of type Object to specify which object raised the event, and one of type EventArgs or a subclass, to provide any extra information. This isn't required by the language, but it's a broadly-followed convention.