【问题标题】:Is WithEvents any different from AddHandler?WithEvents 与 AddHandler 有什么不同吗?
【发布时间】:2014-10-22 04:55:15
【问题描述】:

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

我正在编写如下所示的 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

【问题讨论】:

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


【解决方案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

【讨论】:

  • 谢谢,所以如果 ASPX 页面已经有一个 Init,那么上面 HTTP 模块中编码的那个不是覆盖它吗?两者都将被称为不只是一个?
  • 如果你在一个已经有Handles xxx的方法上调用AddHandler,它会在该事件触发时被调用两次。
  • 好的,那我就不用担心了!这并不重要,但在我上面的示例中,ASPX 中的 Init 会先被调用还是我的 HTTP 模块中的 Init 会被调用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多