我知道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,而是让它接受IList<T>、ICollection<T>或IEnumerable<T>。泛型接口即使对于异构列表也仍然有效,因为System。Object也可以是T。如果您决定在以后使用Stack或其他数据结构,这样做将为您省去麻烦。如果在函数中所需要做的只是逐个遍历它,那么IEnumerable<T>才是真正需要的。
另一方面,当从函数返回一个对象时,您希望为用户提供尽可能丰富的操作集,而不需要他们进行强制转换。在这种情况下,如果内部是List<T>,返回一个List<T>的副本。
在我通常遇到的情况下,我很少直接使用IList。
通常我只是把它用作方法的参数
void ProcessArrayData(IList almostAnyTypeOfArray)
{
// Do some stuff with the IList array
}
这将允许我对. net框架中的几乎任何数组进行泛型处理,除非它使用IEnumerable而不是IList,这种情况有时会发生。
这实际上取决于你需要什么样的功能。我建议在大多数情况下使用List类。当你需要创建一个自定义数组,其中可能包含一些非常特定的规则,你希望将这些规则封装在一个集合中,这样你就不会重复自己的操作,但仍然希望. net将其识别为一个列表时,IList是最好的选择。
我不认为这类事情有严格的规则,但我通常会遵循使用尽可能轻松的方式的指导方针,直到绝对必要的时候。
例如,假设您有一个Person类和一个Group类。Group实例有很多人,所以这里使用List是有意义的。当我在Group中声明列表对象时,我将使用IList<Person>并将其实例化为list。
public class Group {
private IList<Person> people;
public Group() {
this.people = new List<Person>();
}
}
而且,如果你甚至不需要IList中的所有东西,你也可以使用IEnumerable。对于现代的编译器和处理器,我不认为它们真的有任何速度上的差异,所以这只是风格的问题。
使用最低基类型总是最好的。这使接口的实现者或方法的使用者有机会在幕后使用他们喜欢的任何东西。
对于集合,应该尽可能使用IEnumerable。这提供了最大的灵活性,但并不总是适合。
由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;
}
}
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 为什么不是字符串。空一个常数?
- 为什么我不能在c#中有抽象静态方法?
- Nuget连接尝试失败“无法为源加载服务索引”
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?