Returning a ReadOnlyCollection from a method with an IList return type
Here I have the following bit of code:
private IList<IState> _states = new List<IState>();
private ReadOnlyCollection<IState> _statesViewer;
public IList<IState> States { get { return _statesViewer; } }
I believe that generally it is preferable to return interfaces rather than the concret开发者_JS百科e classes themselves, but in this case, shouldn't I set as the return type of the States
property a ReadOnlyCollection
?
Any user of my library will think it is possible to anything you can do with an IList
if I set it as so, and that means adding elements. That is not true and I'm definitely breaking the contract exposing it as an IList.
Am I right with this view or there is something else I am missing here?
Do whatever makes the API clearest. If the caller only needs to enumerate it you could expose as IEnumerable<T>
, but I wouldn't be concerned about exposing it as ReadOnlyCollection
. You could declare a custom type (interface or class) with just an indexer and enumerator, of course
If it was me, I would simply expose it as
IEnumerable<IState>
IEnumerable<T>
is a good choice for any public property that represents a sequence.
It's the smallest contract possible that is still a sequence, which helps you stay decoupled.
It enables a rich collection of operations in Linq for objects, so you're offering your consumer a lot of power.
For some cases i take the IEnumerable<IState>
if people are only allowed to run over the list. But if i need some more built-in functionality for the outer world like index operator, Count, Contains, IndexOf, etc. i'll give them an ReadOnlyCollection
as IList
and write within the documentation that it is read only.
精彩评论