如何使用Delphi 6迭代初始化的枚举类型并避免“越界”错误?

前端之家收集整理的这篇文章主要介绍了如何使用Delphi 6迭代初始化的枚举类型并避免“越界”错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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.
原文链接:https://www.f2er.com/delphi/102185.html

猜你在找的Delphi相关文章