0

嗨,我有以下代码:

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  

有没有一种方法可以让我使用类似 me("_" & ColMap) = ValorLeido 的东西?

4

2 回答 2

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
于 2013-06-06T00:34:07.293 回答
0

这是一个显示CallByName()的简化示例。注意目标变量是Public

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

这是通过Reflection实现的相同的东西,它允许目标变量是Private

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
于 2013-06-06T00:23:42.737 回答