简体   繁体   English

什么是ICollection的返回类型 <Person> 意思?

[英]What does return type of ICollection<Person> mean?

I'm looking at some code samples for Entity Framework 4 and the author created a method that returns ICollection<Person>. 我正在查看Entity Framework 4的一些代码示例,作者创建了一个返回ICollection <Person>的方法。 I know ICollection is an interface. 我知道ICollection是一个接口。 I know Person is the type of object in the collection. 我知道Person是集合中的对象类型。 I know I'm getting back a collection of Persons. 我知道我正在收回一些人物。

The question. 这个问题。 Why ICollection? 为什么选择ICollection? Why not List<>? 为什么不列出<>? Why is an interface being used like this? 为什么这样使用接口? I've used interfaces as "blueprints" for classes, specifying the required members but I don't really understand the usage here. 我已经将接口用作类的“蓝图”,指定了所需的成员,但我并不真正理解这里的用法。

It's often better to return interfaces instead of concrete classes in public API. 在公共API中返回接口而不是具体类通常会更好。

This allows the implementation to change later. 这允许实现稍后更改。 For example, it may, in fact, be returning a List<T> at the moment. 例如,它实际上可能正在返回List<T> However, later, an optimization could be made to return a different type of collection which may have better memory efficiency, allow streaming, or one of many other advantages. 然而,稍后,可以进行优化以返回可以具有更好的存储器效率,允许流传输或许多其他优点之一的不同类型的集合。 As long as that class still implements ICollection<T> , the implementation is free to switch without causing a breaking API change. 只要该类仍然实现ICollection<T> ,该实现可以自由切换而不会导致API更改中断。

One of the key points of the GoF Design Patterns book is to program to an interface, not to an implementation. GoF设计模式书的一个关键点是编程到接口,而不是实现。 The reason for this is the freedom it provides. 其原因是它提供的自由。 By returning an interface instead of a specific type, the implementation may more easily be changed in the future without affecting the calling code. 通过返回接口而不是特定类型,将来可以更容易地更改实现,而不会影响调用代码。

Unless your users wants it from you, your API should expose as little implementation details as possible, and in this case using List<Person> is implementation detail. 除非您的用户想要它,否则您的API应尽可能少地公开实现细节,在这种情况下,使用List<Person>是实现细节。 For example, if you or your users know that they want to access result set by index, than maybe it better return IList<Person> instead of ICollection<Person> , but if you not sure about users scenarios you should expose the most base abstractions as you can (ie in this case maybe IEnumerable<Person> would be enough). 例如,如果您或您的用户知道他们想要通过索引访问结果集,那么最好还是返回IList<Person>而不是ICollection<Person> ,但如果您不确定用户场景,则应该公开最基本的抽象你可以(即在这种情况下可能IEnumerable<Person>就足够了)。

And remember, if lately you decide use more derived return type, it wouldn't break any existing clients, but you can't use more based return type without break some of them. 请记住,如果最近您决定使用更多派生返回类型,它不会破坏任何现有客户端,但您不能使用更多基于返回类型而不会破坏其中一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM