Jump to content
RaelB

Is it possible to write "generic" code for TObjectList<T> descendants?

Recommended Posts

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 by RaelB
add a point

Share this post


Link to post

Derive Notes and Books from common generic class that is child of TObjectList with all the common methods you want

Edited by Fr0sT.Brutal

Share this post


Link to post

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 by Clément

Share this post


Link to post

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×