开发者

Delphi: generics and TObjectList

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 imp开发者_开发知识库lemented 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜