I like GameCat's answer (gave it +1) for the description of class constraints.
I have a slight modification of your code that works. Note that since you gave a constraint to say that T must be a descendant of TItem, you can actually just declare ObjectList as TObjectList<TItem>
- no need to use T here.
Alternatively, you could create a proxy of sorts. First, note GameCat's comment about fields being private.
type
TGenericClass<T: TItem> = class
private
type
D = class(TItem); // Proxy to get your T into and object list
private
SimpleList: TList<T>;
ObjectList: TObjectList<D>; // Compiles now, but there is that type issue
public
procedure Add(Item: T); // No direct access to ObjectList
end;
Add is an example of how to access the object list. As it turns out, you can pass Item to ObjectList.Add with no trouble whatsoever:
procedure TGenericClass<T>.Add(Item: T);
begin
ObjectList.Add(Item);
end;
I think that may be a bug though, so to protect yourself against that getting fixed:
procedure TGenericClass<T>.Add(Item: T);
var
Obj: TObject;
begin
Obj := Item;
ObjectList.Add(D(Obj));
end;
Given your scenario though, I'd say TObjectList should do just fine.