2010-06-11 27 views
0

我有一個UInteger類型的鍵字典和值是List(Of Session)其中(公共)類Session包含幾個變量和一個構造函數(Public Sub New(...))。無法從.NET Dictionary獲取List(Of <my class>)?

一些在我Session類的變量是:

Private count As Integer 
Private StartDate As Date 
Private Values As List(Of Integer) 

和幾個類似的方法:

Friend Sub Counter(ByVal c as Integer) 
    count += c 
End Sub 

沒有問題值添加到字典:

Dim Sessions As New List(Of Session) 
Dim dict As New Dictionary(Of Integer, List(Of Sessions)) 

然後一些代碼來填充會話中的幾個會話對象(這裏沒有顯示)然後:

dict.Add(17, Sessions) ''#No problem 
Sessions.Clear() 
Sessions = dict(17) ''#This doesn't return anything! 

即使代碼沒有返回任何錯誤,Sessions對象也是空的。 我的班課程是否會被存儲在字典中?

+0

不應該是這樣:Dim dict As New Dictionary(Of Integer,List(Of Session))?無論如何,你正在清除剛剛添加到該鍵值的列表,因此在dict(17) – Marc 2010-06-11 13:35:59

+0

@Marc:是的時候它將是空的。這讓我困惑。 – 2010-06-11 13:37:08

+0

對不起,你說得對! :) – Magnus 2010-06-14 08:59:09

回答

4

這是因爲Sessions變量是對數據的引用,所以當你將它添加到字典中時,字典中的變量指向相同的東西。因此,當您執行Sessions.Clear()時,您可以清除實際數據,並且由於這兩個參考點位於同一位置,因此它們都不保存數據。

如果您實際上想要擁有兩個不同的數據副本,this討論可能會有幫助。

+0

謝謝,我明白了!一般的答案是,您每次將類添加到任何類型的集合時,都會傳遞引用類型並需要手動處理複製或克隆? – Magnus 2010-06-14 09:04:43

+0

@magsto:是的,這是你必須處理所有參考類型的方式。 – 2010-06-14 09:10:03

1

這些線條看起來腥對我說:

Dim Sessions As New List(Of Session) 

' Your Sessions variable has the same name as a class? ' 
Dim dict As New Dictionary(Of Integer, Sessions) 

' You are adding a List(Of Session) to a Dictionary(Of UInteger, Sessions)? ' 
' This could only be legal if List(Of Session) derived from your Sessions class ' 
' (which is obviously not true). ' 
dict.Add(17, Sessions) 

它也混淆究竟你的意思是在這裏:

Sessions.Clear() 
Sessions = dict(17) 'This does not return anything!' 

通過「不返回任何東西,」你的意思是它返回Nothing一個空的List(Of String)?在後一種情況下,這是預期的:你剛剛清除了你正在談論的列表。在前一種情況下,這很奇怪,我們需要更多細節。

+0

對不起,如Marc所述,它應該是Dim Dictionary作爲新詞典(整數,列表(會話))。 – Magnus 2010-06-14 09:00:29

相關問題