Queue hold reference or object value?
In C#, the following "containers" hold reference or object itself for reference types?
Queue
Stack
Array
List
Vector
For example if I do the following:
Queue<MyItem> item = new Queue<MyItem>(100);
MyItem mit = new MyItem();
item.Enqueue(mit);
The reference of the mit
is copied to item
or the mit
object itself has been moved to item
memory location?
if I say
item = null;
it will not set all objects开发者_JS百科 inside item
to null. Am I right?
The Queue contains a reference to the items in contains. Setting the Queue to null will not affect the items themselves.
It depends on whether the MyItem is a value type (sometimes called struct after the keyword) or refernce type (class). Value type assignments copy the value (i.e. the whole object) while reference types copy the reference.
The reference of the mit is copied to item or the mit object itself has been moved to item memory location?
First of all, I think you're caring way too many about implementaion details.
"The reference of the mit" is kinda meaningless. "mit" is a reference. If I add
mit2 = mit;
, both mit & mit2 reference the same object.Similarly, moving "the mit object itself ... to item memory location" isn't really meaningful in managed code. If I add
item.Enqueue(mit2);
, item now has two entries pointing to the same object.
The reference of the mit is copied to item or the mit object itself has been moved to item memory location?
Not really. If the object in question is a reference type then it is neither moved nor copied. It is more precise to say that a new reference to the same object has been added to the collection. If the object is a value type then it is indeed copied.
if I say
item = null;
it will not set all objects inside item to null. Am I right?
You are correct. It will not do anything to the items contained within the collection regardless of whether they are reference or value types.
精彩评论