Wildcard for arbitrary generic List

谁都会走 提交于 2019-12-04 06:37:18

问题


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?


回答1:


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.




回答2:


The answer is no, this cannot be done. You cannot include in non-generic class, an object of a non-instantiated generic type.



来源:https://stackoverflow.com/questions/22404734/wildcard-for-arbitrary-generic-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!