Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a Generic Collection in Delphi?

I have a Generic collection like this:

TFoo = class;

TFooCollection<T: TFoo> = class(TObjectDictionary<string, T>)
   procedure DoSomething;
end;

It works fine.

Now I need to extend TFooCollection like this:

TBar = class( TFoo );   

TBarCollection<T: TBar> = class(TFooCollection)
   procedure DoSomethingElse;
end;

And the compiler complains that TFooCollection isn't defined. As TBar is inheriting from TFoo, I would like to take advantage of TFooCollection methods (that would work with TFoo and TBar items) and do something else just with TBar Collections.

Is it possible in Delphi?

like image 802
MarcosCunhaLima Avatar asked Jun 09 '16 15:06

MarcosCunhaLima


1 Answers

You knew how to extend the generic collection TObjectDictionary, so simply apply that same technique when extending the generic collection TFooCollection. TObjectDictionary doesn't specify a type by itself — you needed to provide values for its two generic type parameters. One you hard-coded to string, and the other you provided by forwarding the generic type parameter received in TFooCollection.

Likewise, when specifying the base type for TBarCollection, you can either provide a hard-coded value for the TFooCollection type parameter, or you can forward the parameter from TBarCollection. You probably want to do the latter:

type
  TBarCollection<T: TBar> = class(TFooCollection<T>)
  end;
like image 134
Rob Kennedy Avatar answered Sep 21 '22 18:09

Rob Kennedy