An object in heap riddle
In the code below ViewState["L"]
stores a List<string>
. I create a new instance of List
and assign the casted value of a viewstate to it.
List<string> myList = new List<string>();
myList=(List<string>)ViewState["L"];
Response.Write(myList.Equals(ViewState["L"]));// returns True
As you can see, .Equals()
method tells me that the Viewstate object and the List object are the same. Now my question to you guys is how can a List
and a Viewstate
be a reference to the same object? What does the heap memory at that location actually hold?
Update The code below demonstrates that any variable that gets assigned a cast value of the viewstate, are all pointing to the same object.
List<string> myList1 = new List<string>();
myList1.Add("apple");
ViewState["L"] = myList1;
List<string> myList2 = new List<string>();
myList2 = (List<string>)ViewState["L"];
List<string> myList3 = new List<string>();
myList3 = (List<string>)ViewState["L"];;
myList3.Add("orange");//Here myList2 gets an orange too !
I think, Thomas is right.
how can a List and a Viewstate be a reference to the same object?
It's not "a ViewState", but an element of the ViewState. ViewState["L"]
returns an object which is actually a List<string>
(the same one you just assigned to myList
)
I suppose you're talking about ASP.NET
here. Consider that ViewState
is available on server side, before being trasmitted on client, you reference the exact same object allocated on heap on the server.
Hope this helps.
ViewState is actually an object of type StateBag
StateBag is just a container of other objects. the ["L"] in ViewState["L"]
is an indexer into ViewState that returns some object. In this case that object is a List<string>
object
Your Equals()
comparison is saying that the reference held by ViewState["L"]
is equal to the reference held by myList
Hope that helps
链接地址: http://www.djcxy.com/p/82878.html上一篇: 删除在堆上存储数据的堆中的对象
下一篇: 堆谜语中的一个对象