且构网

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

我应该总是返回的IEnumerable< T>代替的IList< T&GT ;?

更新时间:2022-03-13 15:02:41

这要看你为什么使用特定接口。

It really depends on why you are using that specific interface.

例如,的IList< T> 有几种方法不在 present的IEnumerable< T>

For example, IList<T> has several methods that aren't present in IEnumerable<T>:


  • 的IndexOf(T项目)

  • 插入(INT指数,T项目)

  • RemoveAt移除(INT指数)

  • IndexOf(T item)
  • Insert(int index, T item)
  • RemoveAt(int index)

和属性:


  • T这个[INT指数] {搞定;组; }

  • T this[int index] { get; set; }

如果您需要以任何方式这些方法,然后通过各种手段返回的IList&LT; T&GT;

If you need these methods in any way, then by all means return IList<T>.

另外,如果消耗你的的IEnumerable项&lt; T&GT; 结果期待一个的IList&LT; T&GT; ,它将从考虑所需的任何转换,从而优化编译code保存CLR。

Also, if the method that consumes your IEnumerable<T> result is expecting an IList<T>, it will save the CLR from considering any conversions required, thus optimizing the compiled code.