[英]Is the .NET IList<> (generic IList interface) obsolete or not practical?
Well I came across a lot of legacy code that uses IList<> in the function signatures but inside works with List<>. 好吧,我遇到了很多在函数签名中使用IList <>的遗留代码,但在内部与List <>一起使用。
Now only List<> and arrays (int[] implements IList<>) implement IList<>. 现在,只有List <>和数组(int []实现IList <>)实现IList <>。 ArrayList implements the non generic IList and since generics were introduced there is no point in using boxable/unboxable collections.
ArrayList实现了非泛型IList,并且由于引入了泛型,因此使用boxable / unboxable集合毫无意义。
List<> down is still has an array implementation. List <> down仍然具有数组实现。 I do not think is there a point in using arrays in C# anymore.
我认为在C#中使用数组不再有意义。 LinkedList<> does not implements IList<>
LinkedList <>不实现IList <>
And if I think back to the C++ STL containers/collections they did not had interfaces too. 如果我回想C ++ STL容器/集合,它们也没有接口。 From design perspective there was no issue in what to use or make it interchangeable.
从设计的角度来看,使用什么或使其可互换没有问题。 Or you used an iterator, if you wanted interchangeable, here in C# you can use IEnumerable<> if you want and can be flexible and lazy.
或者,如果要互换性,则使用迭代器,在C#中,如果需要,可以使用IEnumerable <>,并且可以灵活而懒惰。
I see no reason to change it to an array and I do not think I can write a better collection class than List<>. 我认为没有理由将其更改为数组,而且我认为我不能编写比List <>更好的集合类。
Now out of pragmatism how bad would it be if I would replace all the IList<> with List<>? 现在出于实用主义,如果我将所有IList <>替换为List <>将会有多严重?
Now only List<> and arrays (int[] implements IList<>) implement IList<>
现在只有List <>和数组(int []实现IList <>)实现IList <>
Not true. 不对。
For example, if you use NHibernate, it has it's own implementation of IList<T>
which it uses to represent lists and if I remember rightly, will throw errors if you expose List<T>
in a mapped entity. 例如,如果您使用NHibernate,它具有
IList<T>
的自己的实现,用于表示列表,如果我没记错的话,如果在映射的实体中公开List<T>
,则会抛出错误。
In general though, exposing the interface, rather than the implementation in your code leaves things more flexible as someone using your code may want to use their custom implementation of IList<T>
and forcing them to use List<T>
when they don't have to is restrictive. 虽然总的来说,暴露接口而不是代码中的实现使事情更加灵活,因为使用代码的人可能想使用其自定义的
IList<T>
实现,并在他们不使用时强制他们使用List<T>
必须是限制性的。
Using interfaces instead of concrete implementation is considered good practice: it's an integral part of the D in SOLID . 使用接口代替具体实现被认为是一种好习惯:这是SOLID中 D不可或缺的一部分。
People can (and do) make their own implementations of IList<T>
. 人们可以(也可以做)自己的
IList<T>
。 If you replace all occurrences of IList<T>
with List<T>
, then you'll break all those uses. 如果用
List<T>
替换所有出现的IList<T>
List<T>
,那么您将中断所有这些使用。
Linked lists can't implement it because they don't allow random access. 链接列表无法实现,因为它们不允许随机访问。 I think
IList<T>
is a good interface, and use it regularly. 我认为
IList<T>
是一个很好的接口,并定期使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.