Home All Groups Group Topic Archive Search About

Can't find reflected field for inherited event.

Author
10 Nov 2007 12:46 AM
OmegaSquared
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

Author
10 Nov 2007 9:01 AM
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

--
Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Author
10 Nov 2007 6:06 PM
OmegaSquared
Thanks, Mattias.  That seems to work perfectly.

AddThis Social Bookmark Button