我应该赞成的IEnumerable< T>或阵列?
在很多项目,我的工作,每当我必须返回一个只读集合,我用的是的IEnumerable< T>
接口,使其输入具体如下所示:
In many projects I work on, whenever I have to return a read only collection, I use the IEnumerable<T>
interface and make it type specific like so:
Public ReadOnly Property GetValues() As IEnumerable(Of Integer)
Get
'code to return the values'
End Get
End Property
大多数时候,我返回一个列表,但在某些功能和只读属性我返回一个数组也供应好吗通过那种客套扩展方法的目的。
Most of the time, I return a List but in some functions and read only properties I return an array which also serves the purpose alright by kind courtesy of Extension Methods.
我的问题是我在违反任何设计原则,通过返回的IEnumerable&LT; T&GT;
的S,而不是特定类型(例如:名单,其中, T&GT;
,的HashSet&LT; T&GT;
,堆栈&LT; T&GT;
或阵列
S)的?
My question is am I violating any design principles by returning IEnumerable<T>
s instead of specific types (e.g.: List<T>
, HashSet<T>
, Stack<T>
or Array
s)?
我一般是preFER 的IEnumerable&LT; T&GT;
为好。最主要的是要问自己有什么实际的(甚至是最小)的功能正在从方法返回(或传递给它,在一个方法参数的情况下)。
I generally prefer IEnumerable<T>
as well. The main thing is to ask yourself what actual (even minimum) functionality is being returned from the method (or passed to it, in the case of a method argument).
如果你需要做的是枚举结果集,那么的IEnumerable&LT; T&GT;
正是这么做的。没有更多,不会少。这使得可以灵活地返回更具体类型在某些情况下如果需要的话,而不会破坏方法的足迹。
If all you need to do is enumerate over a result set, then IEnumerable<T>
does exactly that. No more, no less. This leaves you the flexibility to return more specific types in certain cases if need be without breaking the footprint of the method.