任意通用列表的通配符 [英] Wildcard for arbitrary generic List
问题描述
list1:TList< TObject>
list2:TList< MyType> // MyType extends TObject
[...]
list1:= list2
此外,似乎没有非泛型的超类型的TList,只是IEnumerable。
有没有办法用任意的T?声明TList的占位符/通配符? / p>
这是一个缺少对 Co-and Contravariance 。
但是,如果您知道您只是进行协同的操作(即迭代列表中的元素),则可以将 TList< MyType>
code> TList< TObject> 鉴于 MyType
继承自 TObject
。 / p>
以维基百科文章为例,你可以处理一个列表的动物列表,当你只是循环阅读他们的名字或东西。
但是,您必须小心需要反斜杠的操作(即添加元素)。
再次,您无法放置狗进入动物名单,因为实际上列表是猫列表。
I have a class MyClass, which is not generic and contains and does something with an arbitrary TList. I wish to replace the TList with the generic TList, but MyClass has to stay non-generic. Since Delphi is invariant something like this doesn't work:
list1: TList<TObject>
list2: TList<MyType> //MyType extends TObject
[...]
list1 := list2
Furthermore there seems to be no non-generic Superclass of TList, just IEnumerable.
Is there a way to declare a placeholder/wildcard for TList with an arbitrary T?
This is a problem of missing support for Co- and Contravariance in Delphi.
However if you know that you are just doing operations that are covariant (i.e. iterating the elements in the list) you can just hardcast your TList<MyType>
to TList<TObject>
given that MyType
inherits from TObject
.
Taking the example from the Wikipedia article you can handle a list of cats like a list of animals when you are just looping through and reading their names or something.
But you have to be careful with actions that need contravariance (i.e. adding elements).
Again the example you cannot put a dog into the list of animals because actually the list is a list of cats.
这篇关于任意通用列表的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!