在Delphi 2005就已經加入了For element in collection do statement語法,可以用來歷遍一個集合、數組等等,下面這個是For in 支持的類型:
# Classes.TList
# Classes.TCollection
# Classes.TStrings
# Classes.TInterfaceList
# Classes.TComponent
# Menus.TMenuItem
# ActnList.TCustomActionList
# DB.TFields
# ComCtrls.TListItems
# ComCtrls.TTreeNodes
# ComCtrls.TToolBar
首先來看一個簡單的例子:
procedure ShowListStr(StrList: TStrings);
var
tmpStr: String;
begin
for tmpStr in StrList do
ShowMessage(tmpStr); //這樣就可以歷遍整個SrList的值了,比以前用for i to do 快了很多吧
end;
{再看看這個:(數組歷遍)}
type
TIntArray = array[0..9] of Integer;
TGenericIntArray = array of Integer;
var
IntArray1: array[0..9] of Integer = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
IntArray2: array[1..2] of TIntArray = ((11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(21, 22, 23, 24, 25, 26, 27, 28, 29, 30));
IntArrayTemp: TIntArray;
IGenericIntArray: TGenericIntArray;
i: integer;
begin
for i in IntArray1 do
begin
ShowMessage(IntToStr(i)); //這樣便可以歷遍這個數組,不用再用for High Low等等函數了
end;
for i in IntArray2 do //多維數組的歷遍
for i in IGenericIntArray do
begin
ShowMessage(IntToStr(i));
end;
end;
{看了後是不是覺得歷遍一個數組比以前方便多了.
再看看For in 在字符串中的應用:}
var
C: Char;
Str1,Str2: String;
begin
Str1 := 'Hello Everybody,I am Kevin...';
Str2 := '';
for C in S1 do //這樣就已經歷遍了一個字符串,並進行了拆解...
Str2 := Str2 + C;
if Str1 = Str2 then
ShowMessage('Success!');
end;
{再看看如何歷遍集合型的數據類型的:}
type
TMyThing = (one, two, three);
TMySet = set of TMyThing;
TCharSet = set of Char;
var
MySet: TMySet;
MyThing: TMyThing;
CharSet: TCharSet;
C: Char;
begin
MySet := [one, two, three];
for MyThing in MySet do //歷遍集合
begin
// 做相關的處理
end;
CharSet := [#0..#255];
for C in CharSet do
begin
// 做相關的處理
end;
end.
{下面這個更加有用,歷遍類
這個類必須實現一個公用的方法為:GetEnumerator(),此方法返回的是一個類.而另一個類必須實現一個公用的方法為:MoveNext()和一個名為Current的屬性.方法返回類型為Boolean;看例子:}
type
TMyIntArray = array of Integer;
TMyEnumerator = class
Values: TMyIntArray;
Index: Integer;
public
constructor Create;
function GetCurrent: Integer;
function MoveNext: Boolean; //這個為實現的MoveNext方法
property Current: Integer read GetCurrent;
end;
TMyContainer = class
public
function GetEnumerator: TMyEnumerator; //這個為實現的GetEnumerator的方法.
end;
constructor TMyEnumerator.Create;
begin
inherited Create;
Values := TMyIntArray.Create(100, 200, 300);
Index := -1;
end;
function TMyEnumerator.MoveNext: Boolean;
begin
if Index < High(Values) then
begin
Inc(Index);
Result := True;
end
else
Result := False;
end;
function TMyEnumerator.GetCurrent: Integer;
begin
Result := Values[Index];
end;
function TMyContainer.GetEnumerator: TMyEnumerator;
begin
Result := TMyEnumerator.Create;
end;
var
MyContainer: TMyContainer;
I: Integer;
Counter: Integer;
begin
MyContainer := TMyContainer.Create;
for I in MyContainer do //歷遍,並把TMyEnumerator的Current進行累加...
Inc(Counter, I);
ShowMessage(IntToStr(Counter)); //值為600
end.
{從上面可以看到通過Current就可以實現很大功能了,我們只需把Current的類型變一個,就可以做到很方便的功能.
總結,從For In語法看到,可以給我們編碼時帶來很多方便... }