[英]Dog is Animal but list<Dog> is not list<Animal>. How to use it safely in a generic/polymorphic function?
It is well-known that a Dog
is an Animal
but List<Dog>
is not List<Animal>
( SO question ) 众所周知,
Dog
是Animal
但List<Dog>
不是List<Animal>
(因此, 问题 )
Anyway, if we have a function 无论如何,如果我们有一个功能
void f(Animal a1, Animal a2); // Java
void f(Animal * a1, Animal * a2) // C++
We can safely use f() passing in objects of type Dog / Dog*
我们可以安全地使用f()传入
Dog / Dog*
类型的对象
Now suppose, we want to generalize it as if it has many arguments of type Animal by using a List
of them (and not specifically a multiple argument list ... ). 现在假设,我们想通过使用它们的
List
来概括它,使其具有许多Animal类型的参数(而不是专门针对多参数列表...)。 The List
is not going to be modified by the function, adding a Cat
to a List<Dog>
for instance. 该
List
不会被该函数修改,例如,将Cat
添加到List<Dog>
中。
This: 这个:
void fg (List<Animal>); // Java
void fg (List<Animal *>) // C++
is not going to allow a call passing in a List<Dog> / List<Dog*>
value. 不允许呼叫传递
List<Dog> / List<Dog*>
值。
What is the way to go? 怎么走?
May be in Java 可能在Java中
void fg (List<? extends Animal>)
and in C++ 和在C ++中
template<T>
void fg (List<T>)
Is that ok? 这可以吗?
Are there other alternatives? 还有其他选择吗?
Thanks. 谢谢。
The list is not going to be modified by the function [...].
该列表将不会通过功能[...]进行修改。 What is the way to go?
怎么走?
In Java, declare a parameter of type List<? extends Animal>
在Java中,声明类型为
List<? extends Animal>
的参数List<? extends Animal>
List<? extends Animal>
. List<? extends Animal>
。 This provides a wildcard bounded by Animal type argument to the List
generic parameter. 这提供了以Animal类型参数为界的通配符,该通配符与
List
通用参数有关。 You can read that as a list of any unknown type that extends Animal
. 您可以将其作为扩展
Animal
的任何未知类型的列表来阅读。 The fact that it is an unknown type means that the only type that can be used wherever a value of the List
's type parameter T
is expected is the null type, whose only value is null
. 这是一个未知类型这一事实意味着,无论何时期望
List
的类型参数T
的值都可以使用的唯一类型是null类型,其唯一值为null
。
A List<Dog>
is a type that fits that description, so is a List<Cat>
. List<Dog>
是适合该描述的类型, List<Cat>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.