1

Suppose that I've instanced an object like this:

Dim PerformPageSize as New HtmlToRtf.CPageStyle.CPageSize()

The Object contains some method members which I've put in an Enumeration like this, I mean, the enum strings are the same as the method names:

Friend Enum PageSize
    Auto
    A3
    A4
    A5
    A6
    Folio
    Letter
    Statement
End Enum

And I pass the Enum as parameter in a Method:

Friend Sub Test(Byval _pagesize as PageSize)
End Sub

Well, now my intention (to avoid writting a large Select case and do this efficientlly) is to parse the Enum value name to call the method (which have exactlly the same name)

So I would like to simplify this:

Friend Sub Test(Byval _pagesize as PageSize)

    Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()

    Select Case PageSize

        Case PageSize.Auto
            PerformPageSize.Auto()

        Case PageSize.A3
            PerformPageSize.A3()

        Case PageSize.A4
            PerformPageSize.A4()

        Case PageSize.A5
            PerformPageSize.A5()

            ' Etc...

    End Select

End Sub

Into something like this else:

(I know that this code has no sense, but is just to understand the idea 'cause I don't know how should be a real solution using reflection or anything else):

Friend Sub Test(Byval _pagesize as PageSize)

    Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()

    ' Parse the Enum value as the Method from the object
    Dim Method = PerformPageSize.TryPase(GetType(PageSize), _pagesize).ToString

    ' Call the equivalent method
    PerformPageSize.[Method]()

End Sub
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • That code is in C# but anyways I've tried to translate it to test it without success – ElektroStudios Feb 20 '14 at 02:03
  • A [strategy pattern](http://www.dofactory.com/Patterns/PatternStrategy.aspx) could be more appropriate. [Switch Statements Smell](http://c2.com/cgi/wiki?SwitchStatementsSmell). – thepirat000 Feb 20 '14 at 02:06

1 Answers1

4

You can use reflection like this:

Friend Sub Test(Byval _pagesize as PageSize)

    Dim performPageSize As New HtmlToRtf.CPageStyle.CPageSize()
    Dim pageType As Type = performPageSize.GetType()
    Dim method As MethodInfo = pageType.GetMethod(_pagesize.ToString())
    If Not method Is Nothing Then
        method.Invoke(performPageSize, Nothing)
    End If

End Sub

This should work as long as the methods are public. If not, you'll need to help out the GetMethod() method with a second parameter to specify the visibility of the method.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194