1
votes

I've created a class like

TMyClass = class(TObject)
private
  FList1: TObjectList<List1>;
  FList2: TObjectList<List2>;
public
end;

Now, I want a method FillArray(Content);, which preferably should be implemented once, i.e. no overload. I believe this is possible using generics, but I'm too inexperienced with these beasts to actually implement it. Do anyone have a clue? Thanks in advance!

1
Shouldn't the declaration be TMyClass<List1, List2>? And what is FillArray(Content) supposed to do regarding FList1 and FList2? How is Content declared? - Uwe Raabe
Sorry Uwe, I'm mixing threads. Fill(Content) is some method responsible for filling the lists. And as you probably have guessed, I haven't actually implemented this... I've got to stop asking questions on a declining blood sugar level... :) - conciliator

1 Answers

3
votes

The following I believe will only work in Delphi 2010. As it depends on the declaration of TArray<T> in the system unit, that looks like this:

  TArray<T> = array of T;

Here is unit I have developed to help with TArray to List conversions

unit ListTools;

interface                
uses Generics.Collections;
type
 TListTools = class(TObject)
 public
    // Convert TList<T> to TArray<T>
    class function ToArray<T>(AList: TList<T>): TArray<T>;
    // Append Array elements in AValues to AList
    class procedure AppendList<T>(AList : TList<T>;AValues : TArray<T>);
    // Clear List and Append Values to aList
    class procedure ToList<T>(AList : TList<T>;AValues : TArray<T>);
 end;

implementation

{ TListTools }

class procedure TListTools.AppendList<T>(AList: TList<T>; AValues: TArray<T>);
var
  Element : T;
begin
  for Element in AValues do
  begin
     AList.Add(Element);
  end;
end;

class function TListTools.ToArray<T>(AList: TList<T>): TArray<T>;
// taken from rtti.pas
var
  i : Integer;
begin
  SetLength(Result, AList.Count);
  for i := 0 to AList.Count - 1 do
    Result[i] := AList[i];
end;

class procedure TListTools.ToList<T>(AList: TList<T>; AValues: TArray<T>);
begin
   AList.Clear;
   AppendList<T>(AList,AValues);
end;

end.

Since TList<T>is the parent class for TObjectList<T> this should work with TObjectList<T> although I have not tried it.