有没有办法在Visual Basic (.net)中用变量名调用过程?
例如,变量strColour可以是10个预定义的值之一:绿色、蓝色、黑色、白色、红色、粉色、橙色、黄色、蓝色、紫色。如何处理每一个都在它自己的Sub例程中,colgreen,colblue,colblack等等。
我可以使用大量的if..then..else和select case,但我想要的是像VBA Excel的Run "col“& strColour这样的东西
有可能吗?
发布于 2010-01-20 09:00:16
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发布于 2010-01-20 08:00:37
通过使用反射,这是可能的。
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发布于 2010-01-20 08:05:19
我会使用select case,除非你有非常多的颜色,或者更好地将这些方法重构为一个方法。如果有必要的话,也许是一个通用的。
https://stackoverflow.com/questions/2098130
复制相似问题