何时何时使用列表中使用的IList和 [英] When to use IList and when to use List

查看:112
本文介绍了何时何时使用列表中使用的IList和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道IList的是接口和List的具体类型,但我还是不知道什么时候使用每一个。我现在做的是,如果我不需要我使用的接口排序或的FindAll方法。我对吗?有没有更好的方式来决定何时使用接口或具体类型?

I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?

推荐答案

有两个规则我跟着:

  • 接受,将工作最基本的类型
  • 返回最丰富的输入您的用户将需要

所以写这需要一个集合函数或方法时,把它写不采取列表,但一个IList< T&GT ;,一个ICollection的< T&GT ;,或IEnumerable的< T&取代。通用接口仍然可以工作,甚至对异质列表,因为System.Object的可以是T了。这样做可以节省您的头痛,如果你决定再使用栈或其他一些数据结构的道路。如果所有你需要做的功能是通过它的foreach,IEnumerable的< T>真的是所有你应该问的。

So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.

在另一方面,返回一个对象了函数的时候,你想给用户最富有的可能的操作集他们无需投各地。因此,在这种情况下,如果它是一个List&LT; T&GT;在内部,返回副本作为一个List&LT; T&GT;

On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.

这篇关于何时何时使用列表中使用的IList和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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