Alessio Pambianchi

ASP.NET AJAX ricerche-condivisione
posts - 39, comments - 177, trackbacks - 1

Events.

Ciao, mi hanno posto questa domanda:

data un'istanza di un oggetto e un suo evento è possibile dall'esterno
risalire al metodo associato all'evento stesso?

Ho eseguito un po di googling, ed ho trovato questo prezioso articolo (un po di hacking sugli eventi), a partire dall'articolo ho cercato, e sono riuscito a dare la risposta alla domanda:

Imports System
Imports System.Collections.Generic
Imports System.Reflection

Module test

  Public Sub Main(ByVal args As String())
    Dim cm As New classManager()

    cm.ce.Fire()

    Dim f() As FieldInfo = cm.ce.GetType().GetFields(BindingFlags.Instance Or BindingFlags.NonPublic)
    Dim x As FieldInfo = f(0)
    Dim evtValue As Object = x.GetValue(cm.ce)
    If evtValue IsNot Nothing Then
      Dim evtDelegate As System.MulticastDelegate = TryCast(evtValue, [Delegate])
      Dim delList As [Delegate]() = evtDelegate.GetInvocationList()
      For Each d As [Delegate] In delList
        Console.WriteLine(d.Method.Name)
      Next
    End If
    Console.ReadKey()
  End Sub

End Module

Class classEvento
  Public Event evento As EventHandler

  Public Sub Fire()
    RaiseEvent evento(Me, New EventArgs())
  End Sub
End Class

Class classManager
  Public ce As classEvento

  Public Sub New()
    ce = New classEvento
    AddHandler ce.evento, AddressOf e_esegui
  End Sub

  Private Sub e_esegui(ByVal sender As Object, ByVal e As EventArgs)
    System.Console.WriteLine("Fire Evento." & vbCrLf)
  End Sub

End Class

Considerazioni:

la classe *classEvento* all'interno della funzione *Fire* esegue la *RaiseEvent* in C# è necessario verificare l'evento stesso prima di emetterlo:

if (event != null)
        {
            event(this, e);
        }

Questa differenza perchè la *RaiseEvent* esegue in automatico il controllo a nothing sull'evento.

Tags:

Print | posted on giovedì 11 settembre 2008 10.20 | Filed Under [ ASP.NET AJAX ]

Feedback

Gravatar

# rock racing jersey

Canberra-based 22-year-old Joe Lewis has found refuge at RBS Morgans-ATS following the shock collapse of PureBlack Racing.
09/01/2012 7.03 | rock racing jersey

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 8 and 6 and type the answer here:

Powered by: