星期三, 9月 19, 2012

TStringList的AddObject使用方式

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
type
  PMyRec = ^TMyrec;
  TMyRec = record
    s: string;
    i: Integer;
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  List: TStringList;
  R1,R2: TMyRec;
  str: string;
  i: Integer;
begin
  List := TStringList.Create;

  R1.s := 'abc';
  R1.i := 123;
  str := '我是字符串';
  List.AddObject('1', @R1);           {用 1 表示结构 TMyRec}
  List.AddObject('2', Sender);        {用 2 表示 TButton}
  List.AddObject('3', Self);          {用 3 表示 TForm1}
  List.AddObject('4', Pointer(str));  {用 4 表示 String}

  for i := 0 to List.Count - 1 do
  begin
    case StrToIntDef(List[i], 0) of
      1: begin
           R2 := PMyRec(List.Objects[i])^;
           ShowMessageFmt('%s,%d', [R2.s, R2.i]);       {abc,123}
         end;
      2: ShowMessage(TButton(List.Objects[i]).Caption); {Button1}
      3: ShowMessage(TForm1(List.Objects[i]).Text);     {Form1}
      4: ShowMessage(PChar(List.Objects[i]));           {我是字符串}
    end;
  end;

  List.Free;
end;

end.

字串還是要用record的方式
type
  TStringRec = record
    s: string;
  end;
  PStringRec = ^TStringrec;

implementation

{$R *.dfm}
procedure AddAllFetchParamList(AllFetchParamList1: TStringList; sFinalDate1, sNo1:string);
var
  FindIndex : integer;
  sRec      : PStringRec;
  tmpStr    : string;
begin
  FindIndex := AllFetchParamList1.IndexOf(sFinalDate1);
  if FindIndex>=0 then //表示有找到
  begin
    tmpStr := PStringRec(AllFetchParamList1.Objects[FindIndex])^.s+','+sNo1;
    PStringRec(AllFetchParamList1.Objects[FindIndex])^.s := tmpStr;
  end else begin
    new(sRec);
    sRec.s := sNo1;
    AllFetchParamList1.AddObject(sFinalDate1, TObject(sRec));
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  sl: TStringList;
  i: integer;
begin
  sl:= TStringList.Create;
  try
    AddAllFetchParamList(sl, '2011/01/01', '1');
    AddAllFetchParamList(sl, '2011/01/01', '2');
    AddAllFetchParamList(sl, '2011/03/01', '3');
    AddAllFetchParamList(sl, '2011/01/01', '4');
    AddAllFetchParamList(sl, '2011/03/01', '5');
  finally
    for i := 0 to sl.Count-1 do
      Dispose(PStringRec(sl.Objects[i]));
    sl.Free;
  end;
end;