开发者

List<T> - do I pass objects or references?

Well I have looked into generics and have following question:

List<someClass> list=new List<someClass>

SomeClass MyInstance=SomeClass();

list.Add(MyInstance);

I am not sure what will be added to list - reference or object of reference type (pointing to actual value of MyInstance).

EDIT: Or I will add value (that is reference data type) which points to actual开发者_如何学运维 object?

Thanks


When you deal with reference types you are always dealing with references, so a reference will be added to the list (a copy of the reference actually). You don't actually have a choice; that's how the language works.


Assuming someClass is a reference type (e.g. class) and not a value type (e.g. struct) then its a reference.

Also I admit it would be pretty devilish to define a struct with the name someClass

struct someClass

And here's the obligatory link to the Jon Skeet article on parameter passing.


Since someClass is a reference type, a reference to MyInstance will be copied into the list.


a reference will be added since MyInstance is of reference type


The list will store the reference of the object instead of the object instance.

Actually,the List store value by use array,and array store the reference on the stack and store the object instance on the heap.


If you dispose your object like the following

MyInstance = null

then, you can't read the MyInstance object ,

but you still can read the object in the list,

because you have two references point to the MyInstance ,

In other words,the object has two reference ,

one is

SomeClass MyInstance=SomeClass();

the other one is be stored in the list,

and you just dispose one of them,

so you still can read the list[0]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜