我知道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.

其他回答

有一件重要的事情,人们似乎总是忽视:

你可以将一个普通数组传递给接受IList<T>参数的对象,然后你可以调用IList. add(),并将收到一个运行时异常:

未处理异常:系统。NotSupportedException:集合大小固定。

例如,考虑以下代码:

private void test(IList<int> list)
{
    list.Add(1);
}

如果你像下面这样调用它,你会得到一个运行时异常:

int[] array = new int[0];
test(array);

这是因为使用带有IList<T>的普通数组违反了利斯科夫替换原则。

因此,如果你调用IList<T>. add(),你可能需要考虑使用List<T>而不是IList<T>。

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

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

ArrayList.Adapter(list).Sort()

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

我不认为这类事情有严格的规则,但我通常会遵循使用尽可能轻松的方式的指导方针,直到绝对必要的时候。

例如,假设您有一个Person类和一个Group类。Group实例有很多人,所以这里使用List是有意义的。当我在Group中声明列表对象时,我将使用IList<Person>并将其实例化为list。

public class Group {
  private IList<Person> people;

  public Group() {
    this.people = new List<Person>();
  }
}

而且,如果你甚至不需要IList中的所有东西,你也可以使用IEnumerable。对于现代的编译器和处理器,我不认为它们真的有任何速度上的差异,所以这只是风格的问题。