在对象中重新获得Classed TObjectList

Ric*_* cf 0 delphi delphi-xe2

我创建了一个名为TRecord的类来存储数据.我创建了另一个包含TRecord类作为对象列表的类.我使用TRecord在对象列表中添加记录,然后在完成后将其设置为父类TTableStore.FManyrecords.

我可以检索列表,COUNT显示相同数量的记录,但它不会让我检索每个单独的记录.

问题是我无法访问记录程序/方法甚至定义记录的检索.查看最后一行伪代码:

TRecord = class(TObject)
  private
    FDescription : Variant;
    FDirectDeposit : Double;
  public
    function  GetDescription : Variant;
    function  GetDirectDeposit : Double;
    procedure SetDescription(Value: Variant; DoValidation: Boolean = True);
    procedure SetDirect(Value: Double; DoValidation: Boolean = True);
end;

TTableStore = class(TObject)
  private
    FManyRecords : TObjectList ;
    FTitle2 : Variant;
    FNormalEarn : Double;
  public
    function  GetTitle2 : String;
    function  GetNormalEarn : Double;
    function GetManyRecords: TObjectList;
    procedure SetManyRecords(Value: TObjectList; DoValidation: Boolean = True);
    procedure SetTitle2(Value: String; DoValidation: Boolean = True);
    procedure SetNormalEarn(Value: Double; DoValidation: Boolean = True);
end;

private
  FReportObj : TTableStore;
  FRecord: TRecord;
  objectListTemp: TObjectList;

implementation
  objectListTemp := TObjectList.Create(false);
  FRecord := TRecord.create;

  Frecord.SetDescription…
  Frecord.SetDirect…

  objectListTemp.add(FRecord);

//next...
//(get next record… until eof.)

finally
  FReportObj.SetManyRecords(objectListTemp);

//===================== Retreival

  FReportObj : TTableStore;
  fListOfRecords : TObjectList;
  FCurrentRecord : TRecord;

  fListOfRecords := fReportObj.GetManyRecords;
  fListOfRecords.count // (is ok)
  FCurrentRecord := fListOfRecords.Items[1]     // ?????????
Run Code Online (Sandbox Code Playgroud)

错误是TObjList <> TRecord.我是Delphi的新手,所以这可能很简单.我错过了什么或不理解?谢谢.

Gra*_*ter 7

您需要使用以下内容将TObject转换为TRecord:

FCurrentRecord := TRecord(FListOfRecords.Items[1]);
Run Code Online (Sandbox Code Playgroud)

反过来也可以这样做,你可以这样做:

var
  X: TRecord;
  Y: TObject;
begin
  X := TRecord.Create;
  Y := X;
end;
Run Code Online (Sandbox Code Playgroud)

这是因为编译器知道TRecord来自TObject但是在你的代码中,编译器无法知道列表中的TObject实际上是一个TRecord.

我建议使用泛型而不是TObjectList.这将创建您的对象类型的列表.您可以将其用作TRecordList.

type
  TRecordList = TObjectList<TRecord>;
Run Code Online (Sandbox Code Playgroud)

在创建它时,您应该使用:

  FManyRecords := TRecordList.Create;
Run Code Online (Sandbox Code Playgroud)

为此,您需要在uses子句中包含System.Generics.Collections.