2013-06-05 25 views
0

您好我有下面的代码:vb.net如何引用一个局部变量

Dim ColMap As Integer = Val(Microsoft.VisualBasic.Left(dr("MappedTo").ToString(), 3)) 
Dim ValorLeido As String 

ValorLeido = temp(dr("NoColumn").ToString()) 

Select Case ColMap 
     Case 101 
     _101 = ValorLeido 
     Case 102 
     _102 = ValorLeido 
     Case 103 
     _103 = ValorLeido 
End Select 

是否有我可以使用的东西,像我这样的方式(“_” & ColMap)= ValorLeido?

+1

您需要包括更多的代码,有配发该块是ambigeous的路人怎么回事。或者给你的问题添加一些更具体的细节。很难说你的目标是什么。 – DarrenMB

+0

使用反射在技术上是可行的。如果目标变量是Public,则可以使用传统的CallByName()函数,使语法稍微简单一些。它只会在变量处于Class中时才起作用,但CallByName()不适用于Modules。 –

回答

0

下面是一个简化示例,显示CallByName()。请注意,目标变量是公共

Public Class Form1 

    Public _101 As String 
    Public _102 As String = "{Default Value}" 
    Public _103 As String 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
     Debug.Print("Before: _102 = " & _102) 

     Dim ColMap As Integer = 102 
     Dim ValorLeido As String = "Hello World!" 

     Dim varName As String = "_" & ColMap 
     CallByName(Me, varName, CallType.Let, ValorLeido) 

     Debug.Print("After: _102 = " & _102) 
    End Sub 

End Class 

,并通过反思,这使得目标变量是私人这里是同样的事情:

Imports System.Reflection 
Public Class Form1 

    Private _101 As String 
    Private _102 As String = "{Default Value}" 
    Private _103 As String 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
     Debug.Print("Before: _102 = " & _102) 

     Dim ColMap As Integer = 102 
     Dim ValorLeido As String = "Hello World!" 

     Dim varName As String = "_" & ColMap 
     Dim fi As FieldInfo = Me.GetType.GetField(varName, Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance) 
     fi.SetValue(Me, ValorLeido) 

     Debug.Print("After: _102 = " & _102) 
    End Sub 

End Class 
+0

不同的应用程序设计可能需要使用[Dictionary](http://msdn.microsoft.com/zh-cn/library/xfhwa508.aspx)将两个值关联在一起。 –

0

尝试使用的存储介质意思是将一系列ID保存为一系列值,如字典

Dim ColMap As Integer = Val(Microsoft.VisualBasic.Left(dr("MappedTo").ToString(), 3)) 
Dim ValorLeido As String = temp(dr("NoColumn").ToString()) 
Dim Lookup as New Generic.Dictionary(of Integer,String) 
Lookup(ColMap) = ValorLeido 

' 1 way of Reading values out of a dictionary safely 
Dim Value as string 
Value="" 

if lookup.trygetvalue("101",value) then 
    msgbox("Value for 101 is """ & value & """") 
else 
    msgbox("Value for 101 is not found) 
end if 

你也可以通过一个单一的索引属性访问,如果这种结构已经存在

public property Value(Index as integer) as string 
    get 
     select case index 
      case 101 
        return _101 
      case 102 
        return _102 
      case 103 
        return _103 
      case else 
        Throw new exception("Index not present " & index) 
    end get 
    set (value as string) 
     ' populate with reverse process ... 
    end set 
end property