Using TStringList's AddObject with integers?

一笑奈何 提交于 2019-12-04 17:33:12

问题


Using delphi 7:

  • How can I add an integer to the object portion of a stringlist item, using AddObject?
  • How can I retrieve the integer back from a object property of stringlist item?
  • How do I free all objects and list when done?

回答1:


Q: How can i add an integer to the object portion of a stringlist item, using AddObject?

A: Just cast the integer value to TObject

List.AddObject('A string',TObject(1));

Q:How can a retrieve the integer back from a object property of stringlist item?

A: Cast to integer the Object Value

AValue := Integer(List.Objects[i]);

Q: How do i free all objects and list when done?

A: You don't need free the object list, because you are not assigning memory. so only call the Free procedure of the TStringList.

Try this sample app

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;


Var
  List : TStringList;
  i    : Integer;
begin
  try
    List:=TStringList.Create;
    try
      //assign the string and some integer values
      List.AddObject('A string',TObject(1));
      List.AddObject('Another string',TObject(100));
      List.AddObject('And another string',TObject(300));

      //Get the integer values back   

       for i:=0 to List.Count - 1 do
         Writeln(Integer(List.Objects[i]));

    finally
      //Free the list  
      List.free;
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;

  Readln;
end.


来源:https://stackoverflow.com/questions/7237695/using-tstringlists-addobject-with-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!