XE3随笔9:使用不同的数据类型标记数组

时间:2024-06-01 19:34:50
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls; type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end; var
  Form1: TForm1; implementation {$R *.dfm} //使用 Byte、Word、Boolean 标记数组
procedure TForm1.Button1Click(Sender: TObject);
var
  arr1: array[Byte] of Integer;
  arr2: array[Word] of Integer;
  arr3: array[Boolean] of Integer;
begin
  ShowMessage(IntToStr(Length(arr1))); {256}
  arr1[Low(arr1)]  := ;
  arr1[High(arr1)] := ;
  ShowMessageFmt('%d, %d', [arr1[], arr1[]]); {11, 22}   ShowMessage(IntToStr(Length(arr2))); {65536}
  arr2[]  := ;
  arr2[] := ;
  ShowMessageFmt('%d, %d', [arr2[Low(arr2)], arr2[High(arr2)]]); {33, 44}   ShowMessage(IntToStr(Length(arr3))); {2}
  arr3[False] := ;
  arr3[True]  := ;
  ShowMessageFmt('%d, %d', [arr3[Low(arr3)], arr3[High(arr3)]]); {55, 66}
end; //使用 "子界" 标记数组
procedure TForm1.Button2Click(Sender: TObject);
type
  TC = 'a'..'z';
var
  arr: array[TC] of Integer;
  n1,n2,n3: Integer;
begin
  ShowMessage(IntToStr(Length(arr))); {26}
  arr['a'] := ;
  arr['b'] := ;
  arr['z'] := ;   n1 := arr[Chr()];
  n2 := arr['abc'[]];
  n3 := arr['z'];   ShowMessageFmt('%d,%d,%d', [n1,n2,n3]); {11,22,33}
end; //使用 "枚举" 标记数组
procedure TForm1.Button3Click(Sender: TObject);
type
  TMyEnum = (A, B, C, D);
var
  arr: array[TMyEnum] of Integer;
  i: Integer;
begin
  arr[A] := ;
  arr[B] := ;
  arr[C] := ;
  arr[D] := ;   for i in arr do ShowMessage(IntToStr(i)); { 11/22/33/44 }
end; //还是使用 "枚举" 标记数组
procedure TForm1.Button4Click(Sender: TObject);
type
  TMyEnum = (X=, Y=, Z=);
var
  arr: array[TMyEnum] of Integer;
  i,n1,n2,n3: Integer;
begin
  arr[X] := ;
  arr[Y] := ;
  arr[Z] := ;   i := ; n1 := arr[TMyEnum(i)];
  i := ; n2 := arr[TMyEnum(i)];
  i := ; n3 := arr[TMyEnum(i)];   ShowMessageFmt('%d,%d,%d', [n1,n2,n3]); {11,22,33}
end; end.