Wildcard for an arbitrary generic list

I have a MyClass class that is not generic and contains and does something with any TList. I want to replace TList with a generic TList, but MyClass should remain non-generic. Since Delphi is invariant, something like this does not work:

list1: TList<TObject> list2: TList<MyType> //MyType extends TObject [...] list1 := list2 

Also, there seems to be no universal TList superclass, just IEnumerable.

Is there a way to declare a placeholder / template for a TList with an arbitrary T?

0
generics delphi delphi-xe5
source share
2 answers

This is the problem of the lack of support for Co- and Contravariance in Delphi. However, if you know that you are performing operations that are covariant (i.e., repeating items in a list), you can simply drag and drop TList<MyType> to TList<TObject> , given that MyType inherits from TObject .

Taking the example from the Wikipedia article, you can treat the list of cats as a list of animals, when you just go in cycles and read their names or something like that.

But you have to be careful with actions that require contravariance (i.e. adding elements).

Again, an example, you cannot put a dog in the list of animals, because in fact the list is a list of cats.

+4
source share

Answer: no, this is impossible. You cannot include an object of an unspecified generic type in a non-generic class.

0
source share

All Articles