[英]Visual Basic .net - Call Procedure from a variable name
有沒有辦法用變量名稱調用Visual Basic(.net)中的過程?
例如,變量strColour可以是10個預定義值之一,綠色藍色黑色白色紅色粉紅色橙色黃色靛藍色。 如何處理每一個都在它自己的Sub Routine,colgreen,colblue,colblack等。
我可以使用一堆if..then..else和select case,但我想擁有的東西就像VBA Excel的Run“col”和strColour
可能嗎?
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
通過反射可以實現。
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個方法。 如有必要,也許是通用的。
如果沒有辦法重寫顏色處理子例程,那么就沒有好辦法了。 你有選擇:
看看反思,它會讓你做你想做的事。 但是,最后,代碼可能與您選擇的代碼一樣復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.