Create a method call in .NET based on a string val

2020-02-11 00:09发布

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

12条回答
萌系小妹纸
2楼-- · 2020-02-11 00:54
Type type = GetType();
MethodInfo method = type.GetMethod("Show"+reportName+"Report");
if (method != null)
{
    method.Invoke(this, null);
}

This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke.

查看更多
不美不萌又怎样
3楼-- · 2020-02-11 00:58

Worked for me in VB .Net MSVS 2015

Dim tip As Type = GetType(MODULENAME)'if sub() or function() in module
        Dim method As MethodInfo = tip.GetMethod("MaxV") 'name of function (gets 2 params double type)
        Dim res As Double = 0 'temporary variable
        If (Not Nothing = method) Then 'if found function "MaxV"

            res = method.Invoke(Me, New Object() {10, 20})
        End If
        MsgBox(res.ToString())
查看更多
beautiful°
4楼-- · 2020-02-11 01:01

Python (and IronPython) can do this thing very easily. With .Net though, you need to use reflection.

In C#: http://www.dotnetspider.com/resources/4634-Invoke-me-ods-dynamically-using-reflection.aspx

My quick port to VB.Net:

Private Sub InvokeMethod(instance as object, methodName as string )
            'Getting the method information using the method info class
            Dim mi as MethodInfo = instance.GetType().GetMethod(methodName)

            'invoing the method
            'null- no parameter for the function [or] we can pass the array of parameters
            mi.Invoke(instance, Nothing)
End Sub
查看更多
成全新的幸福
5楼-- · 2020-02-11 01:01

If i understand the question correctly, you'll have to use Reflection to find the method "show" + reportName and then invoke it indirectly:

Half-baked example:

Case "financial" :
{
   Assembly asm = Assembly.GetExecutingAssembly ();

    MethodInfo mi = asm.GetType ("thisClassType").GetMethod ("showFinancialReport");

   if (mi != null)
      mi.Invoke (null, new object[] {});

}

Insert your own logic there to make up the name for the method to call.

See MSDN documentation of MethodInfo and Assembly for details.

查看更多
欢心
6楼-- · 2020-02-11 01:01

Using reflection:

Type t = this.GetType();
try 
{
    MethodInfo mi = t.GetMethod(methodName, ...);

    if (mi != null)
    {
        mi.Invoke(this, parameters);
    }
} 

But I agree with ago, better not change your original code ;-)

查看更多
孤傲高冷的网名
7楼-- · 2020-02-11 01:02

You've got a deeper problem. Your strings are too important. Who is passing you strings? can you make them not do that?

Stick with the switch statement, as it decouples your internal implementation (method names) from your external view.

Suppose you localize this to German. You gonna rename all those methods?

查看更多
登录 后发表回答