编译器禁止更改循环变量。
有一种方法可以包含对for..step
循环的支持。您必须拥有支持泛型的 Delphi 版本 (Delphi-2009+)。
只需在实用程序单元中进行此声明:
Type
ForLoop = record
class procedure Step( Start,Stop,AStep : Integer;
ALoop : TProc<Integer>); static;
end;
class procedure ForLoop.Step(Start,Stop,AStep : Integer; ALoop: TProc<Integer>);
begin
while (start <= stop) do
begin
ALoop(start);
Inc(Start,AStep);
end;
end;
并像这样使用它:
ForLoop.Step( 40000,90000,1000,
procedure ( i : Integer)
begin
ComboBox1.AddItem(IntToStr(i), nil);
end
);
在 Delphi-2005 中,添加了记录方法以及for in
枚举。
知道了这一点,就可以实现另一个具有步进功能的 for 循环。
type
Range = record
private
FCurrent,FStop,FStep : Integer;
public
constructor Step( Start,Stop,AnIncrement : Integer);
function GetCurrent : integer; inline;
function MoveNext : boolean; inline;
function GetEnumerator : Range; // Return Self as enumerator
property Current : integer read GetCurrent;
end;
function Range.GetCurrent: integer;
begin
Result := FCurrent;
end;
function Range.GetEnumerator: Range;
begin
Result := Self;
end;
function Range.MoveNext: boolean;
begin
Inc(FCurrent,FStep);
Result := (FCurrent <= FStop);
end;
constructor Range.Step(Start,Stop,AnIncrement: Integer);
begin
Self.FCurrent := Start-AnIncrement;
Self.FStop := Stop;
Self.FStep := AnIncrement;
end;
现在你可以写:
for i in Range.Step(40000,90000,1000) do
ComboBox1.AddItem(IntToStr(i), nil);
要深入了解此示例的内部工作原理,请参阅more-fun-with-enumerators
.
实现上述两个示例的版本很容易.StepReverse
,我将把它作为练习留给感兴趣的读者。