2014-09-22 75 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

相關問題