delphi tlist object method calling

1.3k Views Asked by At

all,

In Delphi, I created a simple class called T_Test (see below).

T_Test = class(TObject)

private

 F_Int : Integer;

public

  constructor Create(inInt: Integer);
  destructor Destroy; override;

  property Int: Integer read F_Int write F_Int;

  function showInt : String;


end;

constructor T_Test.Create(inInt: Integer);

 begin

  F_Int := inInt;

 end;


destructor T_Test.Destroy;

 begin

  self.Free;

 end;


function T_Test.showInt : String;

 var outputLine : String;


 begin

   result := IntToStr(Int);
   outputLine := result;
   Form1.Memo1.Lines.Add(outputLine);

 end;

Then I have a procedure in which I want to make a TList of T_Test object and call the showInt method function on them.

I tried like this :

procedure testTlist;

 var

  a, b: T_Test;
  i : Integer;

 begin

  a := T_Test.Create(5);
  b := T_Test.Create(10);

 listTest := TList.Create;

 listTest.Add(a);
 listTest.Add(b);


 listTest[i].showInt;


end;

But I keep getting an an that says I have to use a Record, Object or Class Type on the call of 'listTest[i].showInt'

Does anyone know how to call this method ?

2

There are 2 best solutions below

3
On

Martin's answer is correct. But it's worth noting that if you might be adding different classes to your list, a more robust fragment of code would be ...

var pMmember: pointer;

pMember := listTest[i];
if TObject( pMember) is T_Test then
  T_Test( pMember).ShowInt;

Martin's point about TObjectList is quiet correct. Another option to consider would be TList<T_Test>. David's comment about the error in your destructor is correct too.

I note that you did not initialise the value of i. So the fragment above is pretending you did. If you also wanted to check that the index variable was at a valid value, and not call ShowInt if it was invalid, then you could do something like this...

if (i >= 0) and (i < listTest.Count) and (TObject(listTest[i]) is T_Test) then
  T_Test(listTest[i]).ShowInt;

The above code fragment relies on short-circuit boolean evaluation.

0
On

Cast the listTest[i] pointer back to T_Test and then call its method:

T_Test(listTest[i]).showInt;

Alternatively, if available, use a templated TObjectList class to store T_Test instances directly.