gpt4 book ai didi

delphi - 如何使用 Delphi 6 迭代初始化枚举类型并避免 "out of bounds"错误?

转载 作者:行者123 更新时间:2023-12-03 14:49:18 24 4
gpt4 key购买 nike

我使用的是 Delphi 6 Professional。我正在与一个 DLL 库交互,该库声明了一个枚举类型,如下所示:

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 仍然在每次循环调用时将 e 加 1,从而为 e 创建不是枚举类型成员的数值(例如“3”),并导致“越界”错误。如何在 for 循环中迭代枚举类型,从而仅生成枚举类型的有效值?

谢谢。

最佳答案

通过定义一组常量...

type
TExtDllEnum = (ENUM1 = $0, ENUM2 = $1, ENUM3 = $2, ENUM4 = $4, ENUM5 = $8, 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, ENUM2 = $1, ENUM3 = $2, ENUM4 = $4, ENUM5 = $8, ENUM6 = $10);
const
CExtDllEnumSet = [ENUM1, ENUM2, ENUM3, ENUM4, ENUM5, 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.

关于delphi - 如何使用 Delphi 6 迭代初始化枚举类型并避免 "out of bounds"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3817565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com