问一下,有没有一个类,控制循环的,比如一个类,它的值只有 0、1、2,当它的值为2时,加1后的结果为0。
或者可以通过自定义类型的方式得到这种类型?

解决方案 »

  1.   

    i := (i + 1) mod 3;
      

  2.   

    type
      TCircleQueue = class
        private
          FData: Array of Pointer;
          FLength: Integer;
          FIndex: Integer;
          procedure SetLength(const Value: Integer);
          function Next: Integer;
          function Previous: Integer;
          function GetItem: Pointer;
          procedure SetItem(const Value: Pointer);
        protected
          property Item: Pointer read GetItem write SetItem;
        public
          property Size: Integer read FLength write SetLength;
          property Index: Integer read FIndex;
          procedure Queue(const Value: Pointer);
          function Dequeue: Pointer;
          constructor Create;
          destructor Destroy; override;
      end;
    implementation
    constructor TCircleQueue.Create;
    begin
      FData := TList.Create;
      SetLength(2);
    end;destructor TCircleQueue.Destroy;
    begin
      FIndex := -1;
      FLength := -1;
      SetLength(FData,0);
      Inherited;
    end;function TCircleQueue.Next: Integer;
    begin
      FIndex := (FIndex + 1) mod FLength;
      Result := FIndex;
    end;function TCircleQueue.Previous: Integer;
    begin
      FIndex := (FIndex + FLength - 1) mod FLength;
      Result := FIndex;
    end;function TCircleQueue.GetItem: Pointer;
    begin
      Result := FData[FIndex];
    end;procedure TCircleQueue.SetItem(const Value: Pointer);
    begin
      FData[FIndex] := Value;
    end;function TCircleQueue.Dequeue: Pointer;
    begin
      Result := Item;
      Next;
    end;procedure TCircleQueue.Queue(const Value: Pointer);
    begin
      Previous;
      Item := Value;
    end;procedure TCircleQueue.SetLength(const Value: Integer);
    begin
      SetLength(FData,Value);
      FLength := Value;
      if FIndex > FLength then
        FIndex := 0;
    end;