I've noticed in other people's code that methods returning generic collections will almost always return an interface (e.g. IEnumerable<T>
or IList&开发者_StackOverflow中文版lt;T>
) rather than a concrete implementation.
I have two related questions. Firstly, why (if at all) is it considered better to return an interface? Secondly, is there a collection interface that includes the Sort method (as List<T>
does)?
For the first question: if you return an interface, you retain more flexibility. You can change the implementation later to return a different concrete type. On the other hand, it obviously gives the caller less information, so they may not be able to perform certain operations. (e.g. if you return List<T>
, the caller can use ConvertAll etc... which they can't if you only declare that you return IList<T>
.) In some situations it's worth specifying the concrete type; I generally prefer to at least start with interfaces, and only move to put the concrete type as the return type if I find that I frequently want to use the extra methods available.
Secondly, no standard collection interfaces have a Sort
method. On the other hand, you could write an extension method to sort any IList<T>
. Personally I usually prefer the LINQ OrderBy
, OrderByDescending
, ThenBy
and ThenByDescending
methods... although they return a new sequence, rather than sorting in place.
From C# - List or IList
If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the user's of your library won't need to update their code since the interface doesn't change.
If you are just using it internally, you may not care so much, and using List may be ok.
We use interfaces to give us more flexibility in our implementation. So if your method has the return type of IEnumerable, you could change the object that it returns from a List to an Array without altering the objects that depend on the method.
It's also expressive: if you are returning an IEnumerable, when the object is being used it's clear to the coder that we only care that it's some sort of collection, rather than a specific type
I can't speak for everyone but generally I do it just because I like to only return what I need.Why pass back a full blown collection when all you need is an enumerable collection that can be iterated over.
As to the other part of your question you can always use an IList and then use LINQ to sort:
list.OrderBy(a=>a.Id);
精彩评论