IList<T> versus Collection<T> as property
I have a class with a internal array field. I want to expose this array as a property, such that it maintains as much funtionallity of the orginal array but does not violate encapsulation by exposing the array direct开发者_如何转开发ly. What are the various methods and pros and cons? I'm thinking specifically about IList<T>
or Colleciton<T>
IList<T>
is bettere as it is a descendant of the ICollection generic interface and is the base interface of all generic lists. Along with you also have advantage for having funcionality from following interfaces
IEnumerable<T> and IEnumerable
this is the signature:
public interface IList<T> : ICollection<T>,
IEnumerable<T>, IEnumerable
see following for details
IList<T> Interface
An IList is an ICollection:
public interface IList<T> : ICollection<T>,
IEnumerable<T>, IEnumerable
You could implement ICollection, and if you need more methods from IList in the future, you can just change it without causing harm to the clients.
The corrrect way to do this is to expose a ReadOnlyCollection
that wraps the array.
If you expose the array as an interface, malicious code can cast it back to an array and modify the values behind your back.
Personally I'd expose it as IEnumerable<T>
and let the client decide which is best since this will give you the most freedom to change the underlying storage. If you really want to use IList<T>
or ICollection<T>
I'd choose ICollection<T>
for the same reason.
精彩评论