Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - Is there a .NET collection interface that prevents adding objects?

I have a class that maintains list of objects of another class. List of objects is a public property. I would like to prevent users from adding and removing objects directly to list like this:

      MyObject.MyListProperty.Add(object);

Instead I want them to use method that will internally do some processing and then add object to list.

I have some ideas:

  • create descendant of List<T> and override add and remove
  • return fresh copy of list through property getter (list is relatively short, not more than 30 objects)

Is there some collection interface that does not have Add and Remove?

Edit:
I'm going to go with ReadOnlyCollection<T>. Reason is that wrapped collection can be updated and changes will be immediately visible in read only object (see MSDN code examples for ReadOnlyCollection<T> and AsReadOnly()). This allows that read only list be created only once.

The problem with IEnumerable is that object can be casted back to original List<T> and then directly manipulated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use ReadOnlyCollection - wrap your collection in this and return the ReadOnlyCollection to users of your class:

return new ReadOnlyCollection(innerCollection);

Or using the AsReadOnly method of the List<T> class:

return innerCollection.AsReadOnly();

The IEnumerable interface will do what you need, as it only has one member GetEnumerator(), that will only let you iterate over items.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...