Delphi新语法 For ..In

首先我们要知道哪些类型可以用For In吧,下面就是:

  • for Element in ArrayExpr do Stmt; 数组
  • for Element in StringExpr do Stmt; 字符串
  • for Element in SetExpr do Stmt; 集合
  • for Element in CollectionExpr do Stmt; 集合
  • for Element in Record do Stmt; 结构体

我们来看例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

type

THuangJacky = (hjA,hjB,hjC,hjD);

TJackyHuang =record

a,b,c:Integer;

end;

const

stringExpr='HuangJacky';

arrayExpr:array[0..5]ofInteger= (1,2,3,4,5,6);

setExpr:setofTHuangJacky = [hjA,hjB,hjD];

procedureTForm1.FormCreate(Sender: TObject);

var

I:Integer;

C:Char;

D:THuangJacky;

F:TComponent;

begin

forcinstringExprdo

ShowMessage(C);

foriinarrayExprdo

ShowMessage(IntToStr(i));

fordinsetExprdo

ShowMessage(IntToStr(Ord(d)));

forFinSelfdo

ShowMessage(f.Name);

end;

是不是很爽呀?哈哈,Delphi也与时俱进呀.

之前写了类助手文章中,老赵问是不是扩展方法,因为对C#没有了解到这么多,所以不知道.

那么我们在Java中要For In必须实现Iterator吧.

那么Delphi的会不会也要呢?

是的,如果我们要自己的类支持For In的话,就必须满足下面的条件:

1 必须有个公共方法GetEnumerator(),这个方法返回值是一个类,接口或者记录体.

2 上面返回的类,接口或者记录体中又必须有公共方法MoveNext(),这个方法的返回值是Boolean.

3 1中返回的类,接口或者记录体中必须有一个只读的属性Current,类型要和集合中的元素一样.

说了这么多,看个例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

type

TMyIntArray =arrayofInteger;

TMyEnumerator =class

Values: TMyIntArray;

Index:Integer;

public

constructorCreate;

functionGetCurrent:Integer;

functionMoveNext:Boolean;

propertyCurrent:Integerread GetCurrent;

end;

TMyContainer =class

public

functionGetEnumerator: TMyEnumerator;

end;

constructorTMyEnumerator.Create;

begin

inheritedCreate;

Values := TMyIntArray.Create(100,200,300);

Index := -1;

end;

functionTMyEnumerator.MoveNext:Boolean;

begin

ifIndex < High(Values)then

begin

Inc(Index);

Result :=True;

end

else

Result :=False;

end;

functionTMyEnumerator.GetCurrent:Integer;

begin

Result := Values[Index];

end;

functionTMyContainer.GetEnumerator: TMyEnumerator;

begin

Result := TMyEnumerator.Create;

end;

var

MyContainer: TMyContainer;

I:Integer;

Counter:Integer;

begin

MyContainer := TMyContainer.Create;

Counter :=0;

forIinMyContainerdo

Inc(Counter, I);

WriteLn('Counter = ', Counter);

end.

https://blog.csdn.net/rocklee/article/details/48627165