简体   繁体   中英

Do extension methods like `ToArray` and `ToList` operate by reference or by value?

Let's say I have a private dictionary or a list in my class. I want to return a readonly enumerator so that others can iterate over the list, but not have access to modify the items.

Instead of creating a wrapper class around the original, I'd like to return copies of the original items/elements. Will something like original.ToList<Type>().GetEnumerator() return a list with references to the original items, or a list with copies of the original items?

I should note that I also need indexing (ie accessing items by index, still not being able to modify them).

The methods create a new instance of the collection, but the item references will still be to the old items. In other words, a consumer could not update your internal collection, but they could update the items themselves.

Assuming you have appropriate encapsulation around modifying the items, this approach will work, though it is a little memory-intensive for larger lists, since you need to allocate memory for each new item reference. That's one reason why returning a wrapper is often preferred: it reduces the extra memory required to a single instance of the wrapper class.

ToList() and Torray() both work by value . They simply copy the values from the original IEnumerable<> to the new container.

But the values being copied might very well be references.

The straight call to

original.ToList<MyType>()

will create a "shallow" copy: the list will be new, but the objects will be the same.

If you would prefer a "deep" copy, you can use LINQ to duplicate your items before adding them to the list:

original.Select(item => new MyType(item)).ToList()

Assuming that your class has a constructor that takes an instance of itself and produces a copy, similar to a copy constructor of C++, this would produce a list of copies of your objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM