Should I always return IEnumerable instead of IList?

后端 未结 14 1990
一生所求
一生所求 2020-11-27 11:47

When I\'m writing my DAL or other code that returns a set of items, should I always make my return statement:

public IEnumerable GetRecentItems         


        
14条回答
  •  孤城傲影
    2020-11-27 12:27

    I think you can use either, but each has a use. Basically List is IEnumerable but you have count functionality, add element, remove element

    IEnumerable is not efficient for counting elements

    If the collection is intended to be readonly, or the modification of the collection is controlled by the Parent then returning an IList just for Count is not a good idea.

    In Linq, there is a Count() extension method on IEnumerable which inside the CLR will shortcut to .Count if the underlying type is of IList, so performance difference is negligible.

    Generally I feel (opinion) it is better practice to return IEnumerable where possible, if you need to do additions then add these methods to the parent class, otherwise the consumer is then managing the collection within Model which violates the principles, e.g. manufacturer.Models.Add(model) violates law of demeter. Of course these are just guidelines and not hard and fast rules, but until you have full grasps of applicability, following blindly is better than not following at all.

    public interface IManufacturer 
    {
         IEnumerable Models {get;}
         void AddModel(Model model);
    }
    

    (Note: If using nNHibernate you might need to map to private IList using different accessors.)

提交回复
热议问题