想要在vb.net中使用字符串值以名称访问变量

时间:2014-09-22 10:03:27

标签: .net vb.net variables

网。我试图从字符串值访问变量作为其名称。

我创建了近50个类类型的变量,如A1,A2,A3作为Class类型。并且还有一个包含数据表中50项的列表。我想要的是,当访问像

    dim dr as datarow
    for each dr in dt.rows
    dim newstring as string = dr(0).tostring
    'Here I have the problem, newstring will return A1 or A2 or A3 and I dont want to use if-then or Select case statements becose
it will lead me toward hundreds of lines. I want to access newstring.property=something 

    Next

问题是上面会返回一个字符串值,并且我声明了一个与返回的新闻字符串同名的变量。我想只访问名称为newstring的变量。请帮我。

1 个答案:

答案 0 :(得分:0)

您应该为每个座位创建一个课程

Private Class Seat
    Public Property Name As String
    Public Property IsReserved As Boolean
    Public Sub New(ByVal name As String)
        Me.Name = name
    End Sub
End Class

使用每个席位填充一个列表(这些可以按您想要的顺序排列)

'create your seats
Dim seats As New List(Of Seat)
seats.Add(New Seat("A3"))
seats.Add(New Seat("B6"))
seats.Add(New Seat("A1"))
'etc.

然后,您可以使用linq表达式查找与数据库中的名称匹配的席位:

'find the seat in the list that matches the name
Dim dr As DataRow
For Each dr In dt.rows
    Dim newstring As String = dr(0).ToString
    Dim seat = seats.Find(Function(x) x.Name = newstring)
    seat.Property = Something
Next