二、體驗TList<T>
在此,我將使用以前版本的指針集合類TList與TList<T>作對比,保存一組整形數據。使用控制台的方式進行程序編寫。
1program TestTList;
2
3{$APPTYPE CONSOLE}
4
5uses
6 SysUtils,
7 Classes,
8 Generics.Collections; // 泛型集合命名空間,太優美了!
9
10var
11 intList: TList<Integer>;
12 oldList: TList;
13 n, elem: Integer;
14 pTmp: Pointer;
15begin
16 // 以下代碼測試舊的集合對象
17 oldList := TList.Create;
18 oldList.Add(Pointer(1));
19 oldList.Add(Pointer(2));
20 oldList.Add(Pointer(3));
21
22 Writeln('TList start');
23
24 for n := 0 to oldList.Count - 1 do
25 begin
26 Writeln(Integer(oldList[n]));
27 end;
28
29 for pTmp in oldList do
30 begin
31 Writeln(Integer(pTmp));
32 end;
33
34 FreeAndNil(oldList);
35
36 // 以下代碼測試整形泛型集合對象
37 intList := TList<Integer>.Create;
38 intList.Add(1);
39 intList.Add(2);
40 intList.Add(3);
41
42 Writeln( #13 + #10 + 'TList<T> start');
43
44 for n := 0 to intList.Count - 1 do
45 begin
46 Writeln(intList[n]);
47 end;
48
49 for elem in intList do
50 begin
51 Writeln(elem);
52 end;
53
54 FreeAndNil(intList);
55
56 // ----------------------------------------------------------
57 Writeln('press any key');
58 Readln;
59end.
運行結果:
圖2