Let's say I开发者_如何学JAVA have a property:
public Collection<T> GameCollection
{
get { return new Collection<T>(_myGameList); }
}
Would this method creates new Collection object every time it's called?
Yes, it would, because of the new
. However it does not duplicate myGameList
or its contents; it only makes new wrappers for the same myGameList
(see Collection(IList<T>)
constructor).
If you want to prevent any of that and return a single collection, you can initialize a backing field instead and have your getter get that field (assuming _myGameList
is already initialized too):
private Collection<T> _myGameCollection = new Collection<T>(_myGameList);
public Collection<T> GameCollection
{
get { return _myGameCollection; }
}
It would create a new instance of Collection<T>
, but each new instance would wrap the same underlying collection. (Per the docs, the constructor overload that takes IList<T>
wraps the existing collection.)
So you'd return a new Collection<T>
instance every time someone reads the property (which is wasteful and will cause a lot of garbage collection), but it would be returning something that logically acts like the same collection each time.
Yes, it would. When you use the new
keyword you always create a new instance.
Yes, it will create a new collection, but that's not as bad as it sounds.
For most types, the new collection only contains references to each item. In other words, it's only about an extra 4 bytes of RAM per object in the collection, rather than the cost of duplicating all the objects. The exception, of course, is value types, but you need to be careful with using those anyway.
精彩评论