我正在使用Delphi 6 Professional.我正在与DLL libraty接口,它声明了一个enumberated类型,如下所示:
TExtDllEnum = (ENUM1 = $0,ENUM2 = $1,ENUM3 = $2,ENUM4 = $4,ENUM5 = $8,ENUM6 = $10);
如您所见,初始值不是连续的.如果我尝试使用for循环迭代类型,如下所示:
var e: TExtDllEnum; begin for e := Low(TExtToDllEnum) to High(TExtToDllEnum) do ... // More code end;
Delphi仍然将每个循环调用增加1,从而为e创建不是枚举类型成员的数值(例如,’3′),并导致“越界”错误.如何在for循环中迭代枚举类型,该循环只生成枚举类型的有效值?
谢谢.
解决方法
通过定义一组常量……
type TExtDllEnum = (ENUM1 = $0,ENUM6 = $10); const CExtDllEnumSet = [ENUM1,ENUM2,ENUM3,ENUM4,ENUM5,ENUM6]; var e: TExtDllEnum; begin e := Low(TExtDllEnum); while e <= High(TExtDllEnum) do begin if e in CExtDllEnumSet then WriteLn(Ord(e)); Inc(e); end; ReadLn; end.
并实现为迭代器 – 只是为了好玩…
type TExtDllEnum = (ENUM1 = $0,ENUM6 = $10); const CExtDllEnumSet = [ENUM1,ENUM6]; type TMyIterator = class private FValue: TExtDllEnum; public constructor Create; function Next: TExtDllEnum; function HasNext: Boolean; end; constructor TMyIterator.Create; begin FValue := Low(TExtDllEnum); end; function TMyIterator.HasNext: Boolean; begin Result := FValue <= High(TExtDllEnum); end; function TMyIterator.Next: TExtDllEnum; begin Result := FValue; repeat Inc(FValue); until (FValue in CExtDllEnumSet) or (FValue > High(TExtDllEnum)) end; var MyIterator: TMyIterator; begin MyIterator := TMyIterator.Create; while MyIterator.HasNext do WriteLn(Ord(MyIterator.Next)); MyIterator.Free; ReadLn; end.