Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

TStringList implementing Integers[] array property

Title: TStringList implementing Integers[] array property Question: I often store integer values in the Objects[] array property of a TStringList. This involves type casting the integer value as a TObject for the method AddObject() or Objects[] array and back to integer when accessing the Objects array. The following example demonstrates what I mean ... var oList : TStringList; oList := TStringList.Create; oList.AddObject(sSomeString,TObject(iSomeInteger)); // or oList.Objects[iIndex] := TObject(iSomeInteger); iSomeInteger := integer(oList.Objects[iIndex]); This starts to become monotonous when used extensively. I wanted functionality to be able to access this array as plain integers eg. the above becomes .... var oList : TStringListEx; oList := TStringListEx.Create; oList.AddInteger(sSomeString,iSomeInteger); // or oList.Integers[iIndex] := iSomeInteger; iSomeInteger := oList.Integers[iIndex]; The following class extension shows how to implement this by adding a method and a new array property to the Stringlist class. This also demonstrates that various array properties can be created in this class that access the Objects[] array as different types (Boolean,TColor etc.) Answer: unit ClassesEx; interface uses Classes; // ========================================================================== // Class Extensions of STD Delphi Classes // // TStringListEx - Extended Stringlist Class // - Extended to access Objects[] array as integer instead of // - having to type cast TObject() and integer() repeatedly. // - function AddInteger(StringValue,IntegerValue) // - array property Integers[Index] // // Mike Heydon 2005 // ========================================================================== type {TStringListEx} TStringListEx = class(TStringList) private procedure SetInteger(AIndex,AValue : integer); function GetInteger(AIndex : integer) : integer; public function AddInteger(const AString : string; AInteger : integer) : integer; property Integers[AIndex : integer] : integer read GetInteger write SetInteger; end; // -------------------------------------------------------------------------- implementation {TStringListEx} // =================================================== // Get:Set Methods for array proprty Integers // =================================================== procedure TStringListEx.SetInteger(AIndex,AValue : integer); begin Objects[AIndex] := TObject(AValue); end; function TStringListEx.GetInteger(AIndex : integer) : integer; begin Result := integer(Objects[AIndex]); end; // ======================================================== // Method to add integers like AddObject adds objects // ======================================================== function TStringListEx.AddInteger(const AString : string; AInteger : integer) : integer; begin Result := AddObject(AString,TObject(AInteger)); end; end.