IEnumerable as return type

前端 未结 10 2291
轮回少年
轮回少年 2020-12-01 10:41

Is there a problem with using IEnumerable as a return type? FxCop complains about returning List (it advises returning Coll

10条回答
  •  盖世英雄少女心
    2020-12-01 11:21

    Returning IEnumerable is OK if you're genuinely only returning an enumeration, and it will be consumed by your caller as such.

    But as others point out, it has the drawback that the caller may need to enumerate if he needs any other info (for example Count). The .NET 3.5 extension method IEnumerable.Count will enumerate behind the scenes if the return value does not implement ICollection, which may be undesirable.

    I often return IList or ICollection when the result is a collection - internally your method can use a List and either return it as-is, or return List.AsReadOnly if you want to protect against modification (e.g. if you're caching the list internally). AFAIK FxCop is quite happy with either of these.

提交回复
热议问题