开发者

C# return non-modifiable list

开发者 https://www.devze.com 2023-01-18 23:13 出处:网络
I have a class which contains a List<Item> I have a getter on the class that returns this. Is there some thing I can do to ensure the user who calls cannot modify the returned List? (Since it\'s

I have a class which contains a List<Item> I have a getter on the class that returns this. Is there some thing I can do to ensure the user who calls cannot modify the returned List? (Since it's a reference type - I believe changes to the returned reference would affect the list stored in the source object)开发者_Go百科


Return your List wrapped in ReadOnlyCollection<T>.

  public ReadOnlyCollection<Item> MyROList {
    get { return new ReadOnlyCollection<Item>(myList); }
  }

  private List<Item> myList = new List<Item>();

More details elsewhere on SO.

Depending on usage of your class, you could allocate the ReadOnlyCollection at construction time and link it to the underlying List. If you expect to always or most of the time need this property, and the underlying List is in place at that time, then this is sensible. Otherwise you could leave the ReadOnlyCollection<Item> class member null and allocate it on demand in the getter if it is null (taking thread safety into account).


Do you want any changes your class makes in the future to be reflected in the returned list? If so, simply

return new ReadOnlyCollection<T>(list);

would be fine.

However, if you want to return a collection which nothing will modify in the future (i.e. a completely independent copy of the original list) you might want to use:

return new ReadOnlyCollection<T>(list.ToList());

(Using LINQ's ToList method is a very simple way of cloning a list.)

Note that if the list's element type is a mutable reference type, changes to the data within the referenced objects would still be visible to everyone, of course.

0

精彩评论

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