我应该总是返回的IEnumerable< T>代替的IList< T&GT ;?
当我在写我的DAL或其他code返回一组项目,我应该总是让我return语句:
When I'm writing my DAL or other code that returns a set of items, should I always make my return statement:
public IEnumerable<FooBar> GetRecentItems()
或
public IList<FooBar> GetRecentItems()
目前,在我的code我一直在尝试使用IEnumerable的尽可能多的,但我不知道这是否是最好的做法?这似乎正确的,因为我回国最通用的数据类型,同时仍然描述是做什么的,但也许这是不正确的事情。
Currently, in my code I have been trying to use IEnumerable as much as possible but I'm not sure if this is best practice? It seemed right because I was returning the most generic datatype while still being descriptive of what it does, but perhaps this isn't correct to do.
这要看你为什么使用特定接口。
It really depends on why you are using that specific interface.
例如,的IList&LT; T&GT;
有几种方法不在 present的IEnumerable&LT; T&GT;
:
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.