tags:

views:

44

answers:

1

I am trying to get a subset of locally declared methods in a webform code behind using GetMethods but cannot figure out the proper BindingFlags settings (see code below)....and some further specific questions:

1) Is it possible to differentiate between Procedures and Functions?
2) Furthermore, I only want to fetch a certain subset of these....is there some way I can decorate the ones I want with an attribute, and then further filter based on that?

Private Sub LoadFunctions()
        Dim thisClass As Type = Me.GetType
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.DeclaredOnly)
            If method.Name.Substring(0, 3) = "Get" Then
                Me.ddlCodeSamples.Items.Add(method.Name)
            End If
        Next
    End Sub
A: 

a) The real source of the problem seemed to be reflecting on the wrong class.....from a webform, you must do:
Dim thisClass As Type = GetType(yourWebFormName)
...not:
Dim thisClass As Type = Me.GetType

b) I think method.ReturnType could be examined to differentiate between a procedure or method.

c) Here is how custom attributes could be used:
http://www.codeguru.com/vb/gen/vb_general/attributes/article.php/c6073

More or less working code:

Private Sub LoadFunctions()
        '....When run from a webform that you want to reflect on the locally defined functions:
        ' This is *incorrect*:
        '   Dim thisClass As Type = Me.GetType
        ' This is *correct* (I'm not sure why though):
        Dim thisClass As Type = GetType(CodeSamples)    '<-- "CodeSamples" is the webform name
        For Each method As MethodInfo In thisClass.GetMethods(BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
            If Not method.IsSpecialName Then    '<-- to exclude property getter/setters, etc
                ' Rather than filtering on function name, could use custom attributes as discussed here:  
                '        http://www.codeguru.com/vb/gen/vb_general/attributes/article.php/c6073
                If method.Name.Substring(0, 3) = "Get" Then
                    Me.ddlCodeSamples.Items.Add(method.Name)
                End If
            End If
        Next
    End Sub
tbone