创建一个方法调用基于.NET的一个字符串值创建一个、方法、字符串值、NET

2023-09-02 10:51:12 作者:spirit(精灵)

现在,我有code,它看起来是这样的:

 私人小组ShowReport(BYVAL所以reportName作为字符串)
    选择案例所以reportName
        案安全
            Me.ShowSecurityReport()
        案配置
            Me.ShowConfigurationReport()
        案RoleUsers
            Me.ShowRoleUsersReport()
        案例否则
            pnlMessage.Visible = TRUE
            litMessage.Text =该报告名为+所以reportName +是无效的。
    最终选择
结束小组
 

有什么办法创造code将用我的方法的命名规则,以简化的东西呢?下面是一些伪code,它描述了我在寻找:

 私人小组ShowReport(BYVAL所以reportName作为字符串)
    尝试
        呼叫(显示+所以reportName +报告)
    抓住EX为例外
        找不到方法
    结束尝试
结束小组
 

解决方案

 类型类型=的GetType();
MethodInfo的方法= type.GetMethod(秀+所以reportName +报告);
如果(方法!= NULL)
{
    method.Invoke(本,NULL);
}
 
VBA 如何把一个数组里的值拼成一个字符串

这是C#,应该很容易把它变成VB。如果你需要传递参数到方法,它们可以在第二个参数来调用添加。

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

解决方案

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.