问题描述
据我所知,如果 S
是 T
的子类,则列表< S>
List< T>
的孩子。精细。但是接口有一个不同的范例:如果 Foo
实现 IFoo
,那么为什么是 List< Foo>
不是(a的例子) List< IFoo>
?
可能没有实际的类 IFoo
,这是否意味着当暴露一个 List< IFoo>
?或者这是一个糟糕的设计,我必须定义自己的集合类 ListOfIFoos
才能使用它们?这对我来说似乎不合理......
考虑到我正在尝试编程接口,那么暴露这样一个列表的最好方法是什么?我目前倾向于在内部实际存储我的 List< Foo>
作为 List< IFoo>
。
List< Foo>
如果不是子类,列出< IFoo>
,因为您无法在其中存储 MyOwnFoo
对象,这也恰好是 IFoo
执行。 () 存储 List< IFoo>
而不是专用的 List< Foo>
的想法是可以的。如果您需要将列表内容转换为实现类型,这可能意味着您的界面不合适。
I understand that, if S
is a child class of T
, then a List<S>
is not a child of List<T>
. Fine. But interfaces have a different paradigm: if Foo
implements IFoo
, then why is a List<Foo>
not (an example of) a List<IFoo>
?
As there can be no actual class IFoo
, does this mean that I would always have to cast each element of the list when exposing a List<IFoo>
? Or is this simply bad design and I have to define my own collection class ListOfIFoos
to be able to work with them? Neither seem reasonable to me...
What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my List<Foo>
internally as a List<IFoo>
.
Your List<Foo>
is not a subclass if List<IFoo>
because you cannot store an MyOwnFoo
object in it, which also happens to be an IFoo
implementation. (Liskov substitution principle)
The idea of storing a List<IFoo>
instead of a dedicated List<Foo>
is OK. If you need casting the list's contents to it's implementation type, this probably means your interface is not appropriate.
这篇关于为什么我不能返回List< Foo>如果要求列出< IFoo> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!