[fpc-pascal]Passing Methods as Callback Procedures?

memsom at interalpha.co.uk memsom at interalpha.co.uk
Mon Dec 16 14:57:49 CET 2002


> Ok,  I've got some code that looks like this:
> 
> fCollection.ForEach(@Self.DoEach);
> 
> Now when DoEach() is called its Self and the Self above
> are not the same...
> 
> Is this supposed to happen?

Yes. 'Self' refers to the Instance you currently reside within. So:

procedure TMyClass.dosomething(..);
begin
  //Self is the instance of TMyClass
end;

procedure TCollection.ForEach(..);
begin
  //Self is the instance of TCollection
end;

Therefore, as 'Self' refers to the Instance the code belongs to, Self will 
differ in every unique class instance.

What is the parameter for the 'TCollection.ForEach' method? I assume it's a 
typed method pointer? You should be able to just use the following:

fCollection.ForEach(DoEach); //assign this within the class that owns 'DoEach'.

You don't *need* to use Self, unless your class is out of scope, for example 
accessed within a 'with' statement and clashes with a class method/property for 
the with'd class. 

e.g.

  procedure TForm1.Button1Clicked(sender: TObject);
  begin
    Caption := 'wabble'; // the form

    with sender as TButton do begin

      Caption := 'wibble'; //the button not the form

      Self.Caption := 'wobble'; //the form

    end;
  end;
 

Matt



---------------------------------------------
This message was sent using Mistral WebMail.
http://www.mistral.co.uk/






More information about the fpc-pascal mailing list