开发者

Can't get a List(Of <my class>) from a Dictionary in .NET?

I have a Dictionary with key of type UInteger and the value is List(Of Session) where the (Public) class Session contains a couple of variables and a constructor (Public Sub New(...)).

Some of the variables in my Session class is:

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

and a couple of methods like:

Friend Sub Counter(ByVal c as Integer)
    count += c
End Sub
开发者_如何学JAVA

There is no problem to add values to the Dictionary:

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

then some code to fill up a couple of Session objects in Sessions (not shown here) and then:

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

The Sessions object is empty even if the code doesn't returned any error. Is my class Session to compex to be stored in a Dictionary?


That's because the Sessions variable is a reference to the data, so when you add it to the dictionary, the one in the dictionary is pointing to the same thing. So when you do Sessions.Clear() you clear the actual data and since both the references point at the same place, neither of them now hold the data.

If you actually want to have two different copies of the data, this discussion might be helpful.


These lines seem fishy to me:

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)

It's also confusing what exactly you mean here:

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

By "doesn't return anything," do you mean it returns Nothing or an empty List(Of String)? In the latter case, that's expected: you just cleared the very list you're talking about. In the former case, that is very strange, and we'll need more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜