且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在返回的IList< T>不是返回T []或者List<差; T> ;?

更新时间:2021-10-18 15:25:29

也许这并不直接回答你的问题,但在.NET 4.5+,我宁愿追随设计公共或受保护的API,当这些规则:

Maybe this is not directly answering your question, but in .NET 4.5+, I prefer to follow these rules when designing public or protected APIs:


  • 请返回的IEnumerable&LT; T&GT; ,如果只枚举可用;

  • 请返回 IReadOnlyCollection&LT; T&GT; 如果两个枚举和项目数都可用;

  • 请回 IReadOnlyList&LT; T&GT; ,如果枚举,项目数和索引访问可用;

  • 请返回的ICollection&LT; T&GT; 如果枚举,项目数和修改可用;

  • 请返回的IList&LT; T&GT; ,如果枚举,项目数,索引访问和修改是可用的。

  • do return IEnumerable<T>, if only enumeration is available;
  • do return IReadOnlyCollection<T> if both enumeration and items count are available;
  • do return IReadOnlyList<T>, if enumeration, items count and indexed access are available;
  • do return ICollection<T> if enumeration, items count and modification are available;
  • do return IList<T>, if enumeration, items count, indexed access and modification are available.

最后两个选项假设,这个方法不能返回数组作为的IList&LT; T&GT; 实施

Last two options assume, that method must not return array as IList<T> implementation.