七、體驗泛型方法
1、Delphi2009不支持全局泛型方法,泛型方法只能置於類內或者嵌套在方法內,或者成為類的靜態方法。
2、以下代碼將打印出傳入泛型變量的地址:
1program TestGenericArray;
2
3{$APPTYPE CONSOLE}
4
5uses
6 SysUtils;
7
8type
9 TGeneric = class
10 class procedure PrintAddress<T>(aVal: T);
11 end;
12
13var
14 n: Integer;
15
16{ TGeneric }
17
18class procedure TGeneric.PrintAddress<T>(aVal: T);
19begin
20 Writeln(Integer(@aVal));
21end;
22
23begin
24 n := 10;
25 TGeneric.PrintAddress<Integer>(n);
26end.
八、體驗自定義泛型類1program TestGenericClass;
2
3{$APPTYPE CONSOLE}
4
5uses
6 SysUtils;
7
8type
9 TGenericsClass1<T> = class
10 private
11 fValue: T;
12 public
13 constructor Create(aValue: T); virtual;
14 property Value: T read fValue write fValue;
15 end;
16
17var
18 gc1: TGenericsClass1<Integer>;
19
20{ TGenericsClass1<T> }
21
22constructor TGenericsClass1<T>.Create(aValue: T);
23begin
24 fValue := aValue;
25end;
26
27begin
28 gc1 := TGenericsClass1<Integer>.Create(10);
29 Writeln(gc1.Value);
30 FreeAndNil(gc1);
31
32 Readln;
33end.