2013-06-05 54 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