首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在TList中获取TList对象?

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

Stack Overflow用户
提问于 2013-12-06 18:53:14
回答 3查看 3.4K关注 0票数 1

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-06 19:26:47

由于TList为每个项提供了指针,所以必须将这些项转换为正确的数据类型:

代码语言:javascript
复制
var
  aList: TList;
  aItem: TMyObject;
begin

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

end;

您可以这样做来保存一个变量:

代码语言:javascript
复制
var
  aItem: TMyObject;
begin

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

end;

根据您正在使用的Delphi版本,使用TList<T>TObjectList<T>泛型类会更舒服。不需要演员了!

票数 2
EN

Stack Overflow用户

发布于 2013-12-06 18:59:17

TO1[i]给出了你的对象。

TO2[j]给出了TO1列表。

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

票数 1
EN

Stack Overflow用户

发布于 2013-12-06 20:45:14

代码语言:javascript
复制
 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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20431437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档