|
|
|
Example code : Illustrating basic and indexed properties |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate. unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type // Class with Indexed properties TRectangle = class private fArea : LongInt; fCoords : array[0..3] of Longint; function GetCoord(Index: Integer): Longint; procedure SetCoord(Index: Integer; Value: Longint); public Property Area : Longint read fArea; Property Left : Longint Index 0 read GetCoord write SetCoord; Property Top : Longint Index 1 read GetCoord write SetCoord; Property Right : Longint Index 2 read GetCoord write SetCoord; Property Bottom : Longint Index 3 read GetCoord write SetCoord; Property Coords[Index: Integer] : Longint read GetCoord write SetCoord; constructor Create; end; // The form class itself TForm1 = class(TForm) procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} // TRectangle property 'Getter' routine // TRectangle constructor constructor TRectangle.Create; begin // Give default rectangle coordinates left := 0; right := 100; top := 0; bottom := 100; fArea := 100 * 100; end; function TRectangle.GetCoord(Index: Integer): Longint; begin // Only allow valid index values if (Index >= 0) and (Index <= 3) then Result := fCoords[Index] else Result := -1; end; // TRectangle property 'Setter' routine procedure TRectangle.SetCoord(Index, Value: Integer); begin // Only allow valid index values if (Index >= 0) and (Index <= 3) then begin // Save the new value fCoords[Index] := Value; // And recreate the rectangle area fArea := (right - left) * (bottom - top); end; end; // Main line code procedure TForm1.FormCreate(Sender: TObject); var myRect : TRectangle; i : Integer; begin // Create my little rectangle with default coordinates myRect := TRectangle.Create; // And set the corner coordinates myRect.Left := 22; // Left using direct method myRect.Top := 33; myRect.SetCoord(2,44); // Right using indexed method myRect.SetCoord(3,55); // And ask for these values for i:= 0 to 3 do ShowMessageFmt('myRect coord %d = %d',[i,myRect.GetCoord(i)]); // And show the rectangle area ShowMessageFmt('myRect area = %d',[myRect.Area]); end; end. |
Show full unit code |
myRect coord 0 = 22 myRect coord 1 = 33 myRect coord 2 = 44 myRect coord 3 = 55 myRect area = 484 |