在循环中生成属性名称

时间:2016-01-05 00:10:07

标签: vb.net properties insertonsubmit

我正在尝试找到一种方法,将25列的单个记录加载到数据表中。

我可以列出所有25个名为SPOT1的变量到SPOT25(数据表中的列)但我正在寻找更简洁的方法,比如使用循环或字典。

下面的代码显示了两种方法,一种繁琐的“长”方法,以及一种我试图获得帮助的“简洁”方法。

Public dctMC As Dictionary(Of String, VariantType)
Dim newMC As New MONTE_CARLO()

'long method: this will work but is cumbersome
newMC.SPOT1=999
newMC.SPOT2=887
...
newMC.SPOT25=5

'concise method:  can it be done more concisely, like in a loop for example?
 Dim k As String

For x = 1 To 25
    k = "SPOT" & CStr(x)
    newMC.K = dctMC(k)    'convert newMC.k to newMC.SPOT1 etc
Next

'load record
DATA.MONTE_CARLOs.InsertOnSubmit(newMC)

1 个答案:

答案 0 :(得分:1)

对于其他人,我认为有更好的解决方案,但有可能......

Public Class MONTE_CARLO
  Private mintSpot(-1) As Integer
  Property Spot(index As Integer) As Integer
    Get
      If index > mintSpot.GetUpperBound(0) Then
        ReDim Preserve mintSpot(index)
      End If
      Return mintSpot(index)
    End Get
    Set(value As Integer)
      If index > mintSpot.GetUpperBound(0) Then
        ReDim Preserve mintSpot(index)
      End If
      mintSpot(index) = value
    End Set
  End Property
End Class

...用法

Dim newMC As New MONTE_CARLO
For i As Integer = 0 To 100
  newMC.Spot(i) = i
Next i
MsgBox(newMC.Spot(20))