2014-09-22 78 views
0

net。我尝试从字符串值作为其名称访问变量。想要通过其名称在vb.net中使用字符串值访问变量

我已经创建了几乎50类变量类的类型,如A1,A2,A3作为类类型。并在数据表中包含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。我只想访问那个名称为newstring的变量。请帮帮我。

+2

是否有充分的理由将它们创建为变量而不是o f使用关联数组(例如而不是? – 2014-09-22 10:05:21

+0

它实际上是一个座位计划类型,但座位号码不是按顺序排列的,它们都具有像isvacant一样的属性,保留等将来访问。如果你提出任何其他简单的方法,我会感激。 – Prince 2014-09-22 10:14:20

回答

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 
+0

先生非常感谢您再次帮助我解决我的问题。 – Prince 2014-09-23 09:28:54

相关问题