三、體驗TObjectList<T>
剛開始看到TObjectList的時候我有點不解,既然是泛型,那麼T就不區分值類型和引用類型,為什麼還會多出來一個TObjectList<T>呢?在閱讀了Generic.Collections的源碼和經過試驗後,我終於明白了原因,待我來慢慢分析。
同樣,我將使用Contnrs命名空間下的TObjectList和TObjectList<T>做對比,使用控制台程序進行程序的編寫。
首先創建一個類,該類在創建時,對象將打印“創建 ” + 對象的索引號,銷毀時打印“銷毀 ” + 對象的索引號:
1 unit Felix;
2
3 interface
4
5 uses
6 SysUtils;
7
8 type
9 TFelix = class
10 private
11 fId: Integer;
12 public
13 constructor Create; virtual;
14 destructor Destroy; override;
15 property Id: Integer read fId write fId;
16 end;
17
18 var
19 gCount: Integer;
20
21 implementation
22
23 { TFelix }
24
25 constructor TFelix.Create;
26 begin
27 fId := gCount;
28 Writeln('Constructor Felix ' + IntToStr(fId));
29 Inc(gCount);
30 end;
31
32 destructor TFelix.Destroy;
33 begin
34 Writeln('Destructor Felix ' + IntToStr(fId));
35
36 inherited;
37 end;
38
39 end.
40
1 unit Felix;
2
3 interface
4
5 uses
6 SysUtils;
7
8 type
9 TFelix = class
10 private
11 fId: Integer;
12 public
13 constructor Create; virtual;
14 destructor Destroy; override;
15 property Id: Integer read fId write fId;
16 end;
17
18 var
19 gCount: Integer;
20
21 implementation
22
23 { TFelix }
24
25 constructor TFelix.Create;
26 begin
27 fId := gCount;
28 Writeln('Constructor Felix ' + IntToStr(fId));
29 Inc(gCount);
30 end;
31
32 destructor TFelix.Destroy;
33 begin
34 Writeln('Destructor Felix ' + IntToStr(fId));
35
36 inherited;
37 end;
38
39 end.