代码之家  ›  专栏  ›  技术社区  ›  Pieter van Wyk

Delphi检查类型声明中的变量值

  •  3
  • Pieter van Wyk  · 技术社区  · 14 年前

    如何确定变量的值是否在类型声明的范围内。 前任。

    Type
      TManagerType = (mtBMGR, mtAMGR, mtHOOT);
    
    ...
    
    var
      ManagerType: TManagerType;
    
    ....
    
    
    procedure DoSomething;
    begin
      if (ManagerType in TManagerType) then
        DoSomething
      else
        DisplayErrorMessage;
    end;
    

    谢谢,彼特。

    3 回复  |  直到 12 年前
        1
  •  5
  •   Free Consulting    14 年前
    InRange: Boolean;
    ManagerType: TManagerType;
    ...
    InRange := ManagerType in [Low(TManagerType)..High(TManagerType)];
    

    正如Nickolay O.所指出的-而上面的布尔表达式直接对应于:

    (Low(TManagerType) <= ManagerType) and (ManagerType <= High(TManagerType))
    

    编译程序 没有 对基于单个子范围的立即数集检查成员资格执行优化。因此,[成熟的]优化代码将不那么优雅。

        2
  •  3
  •   David Heffernan    14 年前

    好吧,TManagerType类型的变量必须在该范围内,因为Pascal枚举类型就是这样工作的。唯一不可能的办法就是你在编译器背后做了一些淘气的事。

    另一种写法是:

    InRange(ord(ManagerType), ord(low(ManagerType)), ord(high(ManagerType)))
    
        3
  •  -1
  •   Nickolay Olshevsky    14 年前

    您应该通过以下途径检查: 如果mType>高(TManagerType),则。。。