views:

262

answers:

1

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!

+3  A: 

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.

Robert Love
Your solutione is very interessting - and when this is an answer to the question ... wow, my glass sphere was still blind after reading :-)
Heinz Z.
@Robert: My apologies for leading you astray (see comment to Uwe above). I realize that the problem wasn't properly specified. I don't have time to fix it right now, but I suppose I'll make another post for this...
conciliator