我应该赞成的IEnumerable< T>或阵列? [英] Should I favour IEnumerable<T> or Arrays?

查看:142
本文介绍了我应该赞成的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 Arrays)?

推荐答案

我一般是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.

这篇关于我应该赞成的IEnumerable&LT; T&GT;或阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆