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


当前回答

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.

其他回答

一个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

由FxCop检查的微软指南不鼓励在公共api中使用List<T> -更倾向于IList<T>。

顺便说一句,我现在几乎总是声明一维数组为IList<T>,这意味着我可以一致地使用IList<T>。Count属性,而不是Array.Length。例如:

public interface IMyApi
{
    IList<int> GetReadOnlyValues();
}

public class MyApiImplementation : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
    }
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;
    }
}

IEnumerable 您应该尝试使用最不特定的类型来满足您的目的。 IEnumerable没有IList那么具体。 当您希望循环遍历集合中的项时,可以使用IEnumerable。

IList IList实现了IEnumerable。 当你需要通过索引访问你的集合,添加和删除元素等时,你应该使用IList。

列表 List实现了IList。

我同意李的建议,接受一些参数,但不要回头。

如果你指定你的方法来返回一个接口,这意味着你以后可以自由地更改确切的实现,而消费方法永远不会知道。我认为我永远不需要从List<T>更改,但后来不得不更改为使用自定义列表库,以获得它提供的额外功能。因为我只返回了一个IList<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.