享受代码,享受人生

SOA is an integration solution. SOA is message oriented first.
The Key character of SOA is loosely coupled. SOA is enriched
by creating composite apps.
posts - 98, comments - 2402, trackbacks - 162, articles - 45
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

To use IList or List ?(quiz)

Posted on 2005-09-05 19:28 idior 阅读(5779) 评论(17) 编辑 收藏

有一位朋友在看了我有关List<T>的介绍后, 觉得List<T>的功能很强大, 于是乎看到集合就想用它.
不过之前一直提倡Design to interface, 按照这样的思想我们在变量的声明(declare)以及方法的签名(signature)中还是应该尽可能的使用IList<T>. 如下所示:

class Demo
{
    
private IList<int> list=new List<int>;
    
public void DoSomething(IList<T> l)
    
{
         
//l.Foreach();  U can't do it.
    }

}

于是他就问了我这么一个问题, 既然声明为IList<T>, 又如何使用List<T>所特有的一些方便的功能(比如ForEach方法)呢? 总不能为此将声明改用List<T>, 这样岂不是使用具体对象,破坏了Design to interface的原则.

这个问题很有意思, 恐怕其他的朋友也会有此疑惑, 你觉得应该怎么做呢? 这个问题又给了我们什么启示呢?

提示: 解决办法很简单, 不过其中的思想还是值得我们借鉴的.