Can't find reflected field for inherited event.

G

Guest

In a VB application I have been using reflection to temporarily detach events
during serialization (a technique suggested by Andrea Zanetti & Riccardo
Munisso http://www.devx.com/vb2themax/Article/19835/1763/page/3). The
technique involves using Reflection.EventInfo to get the list of events, then
finding the corresponding hidden event field for each event, recording and
clearing its value and then later (after serialization completes) restoring
the cleared values.

This has been working well, but I have now encountered a problem in a case
where an event has been inherited from a base class. In this case I cannot
find the corresponding hidden field. Here is a small code example that
illustrates the problem:

Public Class BaseClass
Public Event BaseClassEvent()
End Class

Public Class DerivedClass
Inherits BaseClass
Public Event DerivedClassEvent()

Public Sub ScanEvents()
Dim eviaEventList() As Reflection.EventInfo ' List of events.
eviaEventList = Me.GetType.GetEvents()
For intEvent As Integer = 0 To eviaEventList.GetLength(0) - 1
Dim strFldName As String = eviaEventList(intEvent).Name +
"Event"
' Get the hidden field (MulticastDelegate)
Dim fdiEvent As Reflection.FieldInfo
fdiEvent = Me.GetType.GetField(strFldName, _

Reflection.BindingFlags.NonPublic Or _

Reflection.BindingFlags.Instance)
If (fdiEvent Is Nothing) Then
Debug.WriteLine(strFldName & " NOT found.")
Else
Debug.WriteLine(strFldName & " was found.")
End If
Next intEvent
End Sub

End Class

When ScanEvents is invoked, the output is:

DerivedClassEventEvent was found.
BaseClassEventEvent NOT found.

Perhaps the name of the hidden field needs to be modified in the case of an
inherited event, but I can't find any documentation about this.

Does anyone know how to obtain this hidden field (or alternatively, how to
get a list of all hidden fields)? All suggestions appreciated.

Cheers,
Randy
 
M

Mattias Sjögren

Does anyone know how to obtain this hidden field (or alternatively, how to
get a list of all hidden fields)? All suggestions appreciated.

Inherited private fields are never returned by reflection, you have to
use the actual declaring type to retrieve it. So instead of

Me.GetType.GetField

try using

eviaEventList(intEvent).DeclaringType.GetField


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top