RaelB 4 Posted December 27, 2021 (edited) Hi, I create object list collections as below: TNotes = class(TObjectList<TNote>) public ... end; TBooks = class(TObjectList<TBook>) public ... end; etc.. Is there a way I can write some generic code that will be able to take in TNotes or TBooks instances, for e.g.: function ListToJSONString(List: TObjectList<T>): string; begin ... end; I want to call as: s := ListToJSONString(FNotes) or s := ListToJSONString(FBooks) But the function does not compile... Can such a function be declared, or do I need to change my definition of TNotes and TBooks? (I don't like using TObjectList<TNote> or TObjectList<TBook> in my code, since I want to create local (i.e. public) methods for each list type, and it is also simpler writing TNotes instead of TObjectList<TNote> each time) Thanks Edited December 27, 2021 by RaelB add a point Share this post Link to post
Fr0sT.Brutal 900 Posted December 27, 2021 (edited) Derive Notes and Books from common generic class that is child of TObjectList with all the common methods you want Edited December 27, 2021 by Fr0sT.Brutal Share this post Link to post
Clément 148 Posted December 27, 2021 (edited) Have you tried: TBook = Class End; TNote = Class End; TBooks = TObjectList<TBook>; TNotes = TObjectList<TNote>; TSerializeJSON<T : class> = Class private public function ToJSON<T : Class>( aList : TObjectList<T> ) : String; End; And call it : procedure TForm56.FormCreate(Sender: TObject); var lNotes : TNotes; S : TSerializeJSON<TNote>; begin S := TSerializeJSON<TNote>.Create; Memo.Lines.text := S.ToJSON<TNote>(lNotes); end; This is just to give you an idea. I just compiled and posted Edited December 27, 2021 by Clément Share this post Link to post
RaelB 4 Posted December 27, 2021 Thanks, both solutions work for me. with the TSerializeJSON, I can make it a bit simpler (since I am really after a function) TSerializeJSON = class public class function ToJSON<T: class>(AList: TObjectList<T>) : string; end; Then i can call without declaring a variable 🙂 Share this post Link to post