WithEvents与AddHandler有什么不同?

时间:2014-08-28 10:46:49

标签: asp.net .net vb.net .net-3.5 asp.net-3.5

可能不是一个非常好的问题,有点像菜鸟问题,但无论如何......

我正在编写一个HttpModule,如下所示并在线查看很多示例,不幸的是它们都在C#中。他们似乎都在使用AddHandler将方法挂钩到事件。

问题:使用WithEvents与使用AddHandler有什么不同,特别是在代码安全性方面?

Imports System.Web
Imports System.Web.UI    
Public Class MyModule1
    Implements IHttpModule    
    Private WithEvents _context As HttpApplication
    Private WithEvents _page As Page    
    ' <summary>
    '  You will need to configure this module in the web.config file of your
    '  web and register it with IIS before being able to use it. For more information
    '  see the following link: http://go.microsoft.com/?linkid=8101007
    ' </summary>
#Region "IHttpModule Members"    
    Public Sub Dispose() Implements IHttpModule.Dispose    
        ' Clean-up code here    
    End Sub

    Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
        _context = context
    End Sub    
#End Region

    Public Sub OnLogRequest(ByVal source As Object, ByVal e As EventArgs) Handles _context.LogRequest    
        ' Handles the LogRequest event to provide a custom logging 
        ' implementation for it    
    End Sub

    Private Sub _context_PreRequestHandlerExecute(sender As Object, e As System.EventArgs) Handles _context.PreRequestHandlerExecute    
        Dim page As Page = TryCast(_context.Context.CurrentHandler, Page)    
        If Not page Is Nothing Then _page = page    
    End Sub

    Private Sub _page_Init(sender As Object, e As System.EventArgs) Handles _page.Init    
        'Does this affect Inits coded elsewhere?    
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

AFAIK - 没有功能差异。 WithEvents只是手动添加和删除方法处理程序的捷径。

如果WithEvents更“安全”,因为您不必记得之后调用RemoveHandler,但实际上没有其他区别。

为了澄清你 有一个声明为WithEvents的对象,并且每个事件后面都有一个Handles xxx

Private WithEvents Button1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

End Sub

您定义了事件方法并致电AddHandler

Private Button1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler Button1.Click, AddressOf Button1_Click
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) 'No Handles Here

End Sub