我在阅读非专利药时遇到了PEC(Producer 100 and Consumer 101的缩写).
有没有人能给我解释一下在extends
点到10点之间怎么用PECS来解析念力?
我在阅读非专利药时遇到了PEC(Producer 100 and Consumer 101的缩写).
有没有人能给我解释一下在extends
点到10点之间怎么用PECS来解析念力?
tl;dr:"PECS"是从该系列的Angular 来看的.如果你要从一个普通的Collection 中提取only件物品,它是制作人,你应该使用extends
件;如果你是only个填充项目,它是一个消费者,你应该使用super
.如果使用同一个集合同时使用这两种方法,则不应使用extends
或super
.
假设你有一个方法,它的参数是一组东西,但你希望它比只接受Collection<Thing>
更灵活.
Case 1: You want to go through the collection and do things with each item.
Then the list is a producer, so you should use a Collection<? extends Thing>
.
理由是Collection<? extends Thing>
可以包含Thing
的任何子类型,因此当您执行操作时,每个元素都将表现为Thing
.(您实际上不能向Collection<? extends Thing>
添加任何内容(除了NULL),因为您不能在运行时知道集合持有Thing
的哪个specific子类型.)
Case 2: You want to add things to the collection.
Then the list is a consumer, so you should use a Collection<? super Thing>
.
这里的理由是,与Collection<? extends Thing>
不同,Collection<? super Thing>
始终可以容纳Thing
,而不管实际的参数化类型是什么.在这里,你不在乎列表中已经有什么,只要它允许添加Thing
;这就是我所保证的.