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

时间:2010-01-19 23:58:52

标签: .net vb.net

有没有办法在Visual Basic(.net)中使用变量名称调用过程?

例如,变量strColour可以是10个预定义值之一,绿色蓝色黑色白色红色粉红色橙色黄色靛蓝色。如何处理每一个都在它自己的Sub Routine,colgreen,colblue,colblack等。

我可以使用一堆if..then..else和select case,但我想拥有的东西就像VBA Excel的Run“col”& strColour

有可能吗?

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:4)

可以通过反射来实现。

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

答案 2 :(得分:1)

我会使用一个精选案例,除非你有非常多的颜色,或者甚至更好地将这些方法重构为1个方法。如有必要,也许是通用的。

答案 3 :(得分:1)

如果无法重写颜色处理子例程,那么就没有好办法了。你有选择:

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

答案 4 :(得分:0)

看看反思,它会让你做你想做的事。但是,最后,代码可能与您选择的代码一样复杂。