인덱스 프로퍼티

인덱스 프로퍼티

프로퍼티 정의에 인덱스(index)가 있으면 read/write 지정자는 함수와 프로시저여야 해요. 그리고 이 함수들은 정수형 인자 하나를 추가로 받아요.

출처: Indexed properties

본문

인덱스가 있으면 같은 함수로 여러 프로퍼티를 읽거나 쓸 수 있어요. 그러려면 프로퍼티들이 같은 타입이어야 해요. 다음은 인덱스를 가진 프로퍼티의 예시예요.


{$mode objfpc}
 
Type
 
  TPoint = Class(TObject)
 
  Private
 
    FX,FY : Longint;
 
    Function GetCoord (Index : Integer): Longint;
 
    Procedure SetCoord (Index : Integer; Value : longint);
 
  Public
 
    Property X : Longint index 1 read GetCoord Write SetCoord;
 
    Property Y : Longint index 2 read GetCoord Write SetCoord;
 
    Property Coords[Index : Integer]:Longint Read GetCoord;
 
  end;
 

 
Procedure TPoint.SetCoord (Index : Integer; Value : Longint);
 
begin
 
  Case Index of
 
   1 : FX := Value;
 
   2 : FY := Value;
 
  end;
 
end;
 

 
Function TPoint.GetCoord (INdex : Integer) : Longint;
 
begin
 
  Case Index of
 
   1 : Result := FX;
 
   2 : Result := FY;
 
  end;
 
end;
 

 
Var
 
  P : TPoint;
 

 
begin
 
  P := TPoint.create;
 
  P.X := 2;
 
  P.Y := 3;
 
  With P do
 
    WriteLn ('X=',X,' Y=',Y);
 
end.

컴파일러가 X에 할당을 만나면, SetCoord를 첫 매개변수로 인덱스(위 경우 1), 두 번째 매개변수로 설정할 값을 넘겨 호출해요. 반대로 X의 값을 읽을 때는 컴파일러가 GetCoord를 호출하고 인덱스 1을 전달해요. 인덱스는 정수 값만 될 수 있어요.

더 알아보기

  • 프로퍼티 정의(Definition)
  • 배열 프로퍼티(Array properties)
  • 기본 프로퍼티(Default properties)