我知道IList是接口,List是具体类型,但我仍然不知道何时使用每一个。我现在做的是,如果我不需要Sort或FindAll方法,我使用接口。我说的对吗?是否有更好的方法来决定何时使用接口或具体类型?


当前回答

在我通常遇到的情况下,我很少直接使用IList。

通常我只是把它用作方法的参数

void ProcessArrayData(IList almostAnyTypeOfArray)
{
    // Do some stuff with the IList array
}

这将允许我对. net框架中的几乎任何数组进行泛型处理,除非它使用IEnumerable而不是IList,这种情况有时会发生。

这实际上取决于你需要什么样的功能。我建议在大多数情况下使用List类。当你需要创建一个自定义数组,其中可能包含一些非常特定的规则,你希望将这些规则封装在一个集合中,这样你就不会重复自己的操作,但仍然希望. net将其识别为一个列表时,IList是最好的选择。

其他回答

我有两条原则:

接受最基本的工作类型 返回用户需要的最丰富的类型

因此,当编写一个接受集合的函数或方法时,不要让它接受List,而是让它接受IList<T>、ICollection<T>或IEnumerable<T>。泛型接口即使对于异构列表也仍然有效,因为System。Object也可以是T。如果您决定在以后使用Stack或其他数据结构,这样做将为您省去麻烦。如果在函数中所需要做的只是逐个遍历它,那么IEnumerable<T>才是真正需要的。

另一方面,当从函数返回一个对象时,您希望为用户提供尽可能丰富的操作集,而不需要他们进行强制转换。在这种情况下,如果内部是List<T>,返回一个List<T>的副本。

If you're working within a single method (or even in a single class or assembly in some cases) and no one outside is going to see what you're doing, use the fullness of a List. But if you're interacting with outside code, like when you're returning a list from a method, then you only want to declare the interface without necessarily tying yourself to a specific implementation, especially if you have no control over who compiles against your code afterward. If you started with a concrete type and you decided to change to another one, even if it uses the same interface, you're going to break someone else's code unless you started off with an interface or abstract base type.

在我通常遇到的情况下,我很少直接使用IList。

通常我只是把它用作方法的参数

void ProcessArrayData(IList almostAnyTypeOfArray)
{
    // Do some stuff with the IList array
}

这将允许我对. net框架中的几乎任何数组进行泛型处理,除非它使用IEnumerable而不是IList,这种情况有时会发生。

这实际上取决于你需要什么样的功能。我建议在大多数情况下使用List类。当你需要创建一个自定义数组,其中可能包含一些非常特定的规则,你希望将这些规则封装在一个集合中,这样你就不会重复自己的操作,但仍然希望. net将其识别为一个列表时,IList是最好的选择。

一个List对象允许你创建一个列表,添加东西到它,删除它,更新它,索引到它等等。当你只想要一个泛型列表时,List就会被使用,你可以在其中指定对象类型。

另一方面,IList是一个接口。基本上,如果您想创建自己的自定义列表,比如一个名为BookList的列表类,那么您可以使用接口为您的新类提供基本方法和结构。IList用于当你想创建自己的特殊子类来实现List时。

另一个区别是: IList是一个接口,不能被实例化。List是一个类,可以实例化。它的意思是:

IList<string> list1 = new IList<string>(); // this is wrong, and won't compile

IList<string> list2 = new List<string>();  // this will compile
List<string> list3 = new List<string>();   // this will compile

你通常最好使用最通用的可用类型,在这种情况下是IList,甚至更好的是IEnumerable接口,这样你可以在以后方便地切换实现。

然而,在。net 2.0中,有一个恼人的事情——IList没有Sort()方法。您可以使用提供的适配器:

ArrayList.Adapter(list).Sort()