Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Visual Basic.net-从变量名调用过程_.net_Vb.net - Fatal编程技术网

Visual Basic.net-从变量名调用过程

Visual Basic.net-从变量名调用过程,.net,vb.net,.net,Vb.net,是否有方法使用变量名调用Visual Basic(.net)中的过程 例如,变量strcolor可以是10个预定义值中的一个,即绿-蓝-黑-白-红-粉-橙-黄-靛-紫。如何处理每一个都在它自己的子程序中,colgreen、colblue、colblack等等 我可以使用一组if..then..else和select case,但我想要的是类似VBA Excel的Run“col”和strcolor 有可能吗?观察反射,它会让你做你想做的事。但是,最终,代码可能与您选择的代码一样复杂。使用反射是可能

是否有方法使用变量名调用Visual Basic(.net)中的过程

例如,变量strcolor可以是10个预定义值中的一个,即绿-蓝-黑-白-红-粉-橙-黄-靛-紫。如何处理每一个都在它自己的子程序中,colgreen、colblue、colblack等等

我可以使用一组if..then..else和select case,但我想要的是类似VBA Excel的Run“col”和strcolor


有可能吗?

观察反射,它会让你做你想做的事。但是,最终,代码可能与您选择的代码一样复杂。

使用反射是可能的

Dim thisType As Type = Me.GetType()
Dim theMethod As Reflection.MethodInfo = thisType.GetMethod("col" & strColour, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)

If Not theMethod Is Nothing Then
    'this, if you have parameters
    theMethod.Invoke(Me, New Object() { add your parameters here, if any })
    'this, if you don't have parameters
    theMethod.Invoke(Me)
End If

我会使用一个选择案例,除非你有大量的颜色,或者更好地将这些方法重构成1个方法。如果需要,可能是通用的。

如果没有方法重写颜色处理子例程,那么就没有好的方法。您可以选择:

  • ,它允许您获取对象成员(方法和属性)的名称。如果你的例程在一个对象上,你可以使用它
  • 信不信由你,最好有一个大的选择语句!它看起来不雅观,但性能比使用反射要好得多

  • CallByName,见下面的例子。哇,我从来都不知道它的存在!不过,仍然建议在这个或反射上使用一个巨大的Select案例。
    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles Button1.Click
        Dim s As String = "one"
        CallByName(Me, s, CallType.Method) 'Subs must be public
    
        s = "two"
        CallByName(Me, s, CallType.Method) 'Subs must be public
    End Sub
    
    Public Sub one()
        Stop
    End Sub
    
    Public Sub two()
        Stop
    End Sub