Home > Enterprise >  Is it possible to use the same Getter / Setter for properties?
Is it possible to use the same Getter / Setter for properties?

Time:09-17

I have a class with multiple variables, which can be accessed by their own property:

TGame = class(TObject)
   strict private
      FValue1 : Integer;
      FValue2 : Integer;
   private
      procedure SetValue1(const Value : Integer);
      procedure SetValue2(const Value : Integer);
      function GetValue1() : Integer;
      function GetValue2() : Integer;
   public
      property Value1 : Integer read GetValue1 write SetValue1;
      property Value2 : Integer read GetValue2 write SetValue2;

I am wondering, if there is a way to use the same Getter and Setter for different properties, like this:

property Value1 : Integer read GetValue write SetValue;
property Value2 : Integer read GetValue write SetValue;

CodePudding user response:

Yes, this can be achieved using index specifiers:

Index specifiers allow several properties to share the same access method while representing different values.

For example,

type
  TTest = class
  strict private
    FValues: array[0..1] of Integer;
    function GetValue(Index: Integer): Integer;
    procedure SetValue(Index: Integer; const Value: Integer);
  public
    property Value1: Integer index 0 read GetValue write SetValue;
    property Value2: Integer index 1 read GetValue write SetValue;
  end;

{ TTest }

function TTest.GetValue(Index: Integer): Integer;
begin
  Result := FValues[Index];
end;

procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
  FValues[Index] := Value;
end;

Of course, this also works with your original private fields:

type
  TTest = class
  strict private
    FValue1: Integer;
    FValue2: Integer;
    function GetValue(Index: Integer): Integer;
    procedure SetValue(Index: Integer; const Value: Integer);
  public
    property Value1: Integer index 1 read GetValue write SetValue;
    property Value2: Integer index 2 read GetValue write SetValue;
  end;

{ TTest }

function TTest.GetValue(Index: Integer): Integer;
begin
  case Index of
    1:
      Result := FValue1;
    2:
      Result := FValue2;
  else
    raise Exception.Create('Invalid index.');
  end;
end;

procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
  case Index of
    1:
      FValue1 := Value;
    2:
      FValue2 := Value;
  end;
end;

But it almost seems like you would rather need an array property:

type
  TTest = class
  strict private
    FValues: array[0..1] of Integer;
    function GetValue(Index: Integer): Integer;
    procedure SetValue(Index: Integer; const Value: Integer);
  public
    property Values[Index: Integer]: Integer read GetValue write SetValue;
  end;

{ TTest }

function TTest.GetValue(Index: Integer): Integer;
begin
  Result := FValues[Index];
end;

procedure TTest.SetValue(Index: Integer; const Value: Integer);
begin
  FValues[Index] := Value;
end;
  • Related