Right now, I have code that looks something like this:
Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:
Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
You can, using System.Reflection. See this code project article for more information.
The "Closest to your question" solution.
You could make delegates out of those reports, and call them by looking up the matching String in a Hashtable:
That way you can add as many reports as you like, and your ability to reflect them, and the perf hit of reflection, aren't an issue.
You can use reflection. Though personally, I think you should just stick with the switch statement.
Sorry, I'm doing C#. Just translate it to VB.NET.
You could use reflection to do this but to be honest I think it's overcomplicating things for your particular scenario i.e. code and switch() in the same class.
Now, if you had designed the app to have each report type in its own assembly (kinda like an add-in/plugin architecture) or bundled in a single external assembly then you could load the reporting assemblie(s) into an appdomain and then use reflection to do this kinda thing.
Use reflection. In the
System.Reflection
namespace you need to get aMethodInfo
object for the method you want, usingGetMethod("methodName")
on the type containing the method.Once you have the
MethodInfo
object, you can call.Invoke()
with the object instance and any parameters.For Example:
Reflection API allows you to get a
MethodInfo
from a method, then callingInvoke
dynamically on it. But it is overkill in your case.You should consider having a dictionary of delegates indexed by strings.