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