如何在TList中获取TList的对象?

时间:2013-12-06 18:53:14

标签: delphi pascal lazarus

假设我在TO1中存储了多个对象:TList然后我创建多个TO1并将它们全部放在TO2:TList中。如何在TO2中的选定TO1中获取所选对象的值?

3 个答案:

答案 0 :(得分:2)

由于TList为每个项目提供了指针,因此必须将项目转换为正确的数据类型:

var
  aList: TList;
  aItem: TMyObject;
begin

  aList := TList(TO2[selectedO2Index]);       // this cast isn't really needed
  aItem := TMyObject(aList[selectedO1Index]); // neither this one!

end;

您可以通过以下方式保存一个变量:

var
  aItem: TMyObject;
begin

  // Now the cast to TList is needed!
  aItem := TMyObject(TList(TO2[selectedO2Index])[selectedO1Index]);

end;

根据您使用的Delphi版本,使用TList<T>TObjectList<T>泛型类会更方便。不需要演员阵容!

答案 1 :(得分:1)

TO1[i]提供了您的对象。

TO2[j]会提供您的TO1列表。

因此TO2[j][i]也给出了对象。

答案 2 :(得分:0)

 type
  TmyObject = class
           text : string;

  end;


procedure TForm2.Button1Click(Sender: TObject);
var
  MotherList : Tlist;
  ChildList : TList;
  obj1 : TmyObject;
begin
//create mother list
MotherList := Tlist.Create;
//create child lista
ChildList := TList.create;


//fill mother list
MotherList.Add(ChildList);    

//fill child list
obj1:= TmyObject.Create;
obj1.text := 'Element 1';
ChildList.Add(obj1);    

//search element of child list within mother list
showmessage(TmyObject(TList(MotherList.Items[0]).Items[0]).text);

obj1.Free;
ChildList.free;
MotherList.free;
end;
相关问题