泛型_Tlist存储对象

1、创建窗口对象  TForm1 = class(TForm)

2、创建列表  List : TList<TBase>;

3、创建列表元素   Base : TBase;   

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 7   Dialogs, StdCtrls, Buttons, Generics.Collections;
 8 
 9 type
10   TForm1 = class(TForm)
11     Memo1: TMemo;
12     Button1: TButton;
13     Edit1: TEdit;
14     rb1: TRadioButton;
15     procedure Button1Click(Sender: TObject);
16   private
17     { Private declarations }
18   public
19     { Public declarations }
20   end;
21 
22   TBase = class
23   private
24     a: Integer;
25     b: Integer;
26     Arr : Array[0..2] of Integer;
27   protected
28     function GetSum(index: Integer) :Integer;
29     Procedure SetData(index: Integer; i: Integer);
30     property data1: Integer index 0 read GetSum write SetData;
31     property data2: Integer index 1 read GetSum write SetData;
32   end;
33 
34 var
35   Form1: TForm1;
36 
37 implementation
38 
39 {$R *.dfm}
40 
41 { TBase }
42 
43 Procedure TBase.SetData(index: Integer; i: Integer);
44 begin
45   Arr[index] :=i;
46 end;
47 
48 function TBase.GetSum(index: Integer) :Integer;
49 var
50   sum : integer;
51 begin
52  Result := Arr[index] * 2;
53  end;
54 
55 procedure TForm1.Button1Click(Sender: TObject);
56 var
57   List : TList<TBase>;
58   Base : TBase;
59   I : Integer;
60 begin
61  // Memo1.Clear;
62   List := TList<TBase>.Create;
63   Base := TBase.Create;
64   Base.data1 :=3;
65   Base.data2 :=5;
66   List.Add(Base);
67   for I := 0 to List.Count - 1 do
68   begin
69   Memo1.Lines.Add(IntToStr(TBase(List[I]).GetSum(0)));
70   Memo1.Lines.Add(IntToStr(TBase(List[I]).GetSum(1)));
71   end;
72   FreeAndNil(Base);
73 end;
74 
75 end.
原文地址:https://www.cnblogs.com/zhrong/p/5695683.html