开发者

What's happening to my lists?

why does

List<Object> objectList; = some objects

List<Object> getList() 
{
  return objectList; //or return new L开发者_如何学运维ist<Object>(objectList);
}

return a list with all items referenced to the original list's items?

Thanks.


In the first case you just return a reference to the list.

In the second case (new List<Object>(list)) the objects are not copied: only the references are copied! You have to clone each item in the collection to return a deep copy of the list.

EDIT:

Iterate through your whole list and create a copy of each of your objects and put them into a new list.

See this for creating deep copies of custom objects. I would suggest not to use the interface ICloneable. Make some research to learn why. :)


It is a reference

You're returning a reference to ObjectList. : )

AboutTheConstructor:

From MSDN: List<(Of <(T>)>)(IEnumerable<(Of <(T>)>)) Initializes a new instance of the List<(Of <(T>)>) class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.


Basically, because List<> and Object are reference types. If you read up on reference/value types in C# here: http://msdn.microsoft.com/en-us/library/3ewxz6et(v=VS.100).aspx it should make sense to you.


if you are using a custom object, Implement the ICloneable interface on the object.

Then, when you are returning your list, clone the objects into a new list. When you pass your old list into the constructor of your new list, you are passing references to all the objects in the original list, unless they are value type (string, int, etc)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜