How to store events in a TList (2) (Views: 29)
Problem/Question/Abstract: What I am trying to achieve is to let many different objects attach to a single event. I did it with Interfaces but I want to do it with normal methods now. My first attempt was to simply store a pointer in a TList, but of course it did not work. I did not think about the Code and Data pointers. My question: How do I store methods in a list in a generic way? I do not want to specify the event type in my base class, only in my specialized classes. Answer: The problem is that a TNotifyEvent is more than a pointer: it includes both data and class information. In any case, here is a solution for you. Drop two buttons on a form, and link the Unit1 code in below. unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Contnrs, StdCtrls; type TNotifyEventObj = class private FNotifyEvent: TNotifyEvent; public constructor Create(aNE: TNotifyEvent); property NotifyEvent: TNotifyEvent read FNotifyEvent write FNotifyEvent; end; TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } FList: TObjectList; FCount: integer; procedure CountEvent(Sender: TObject); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddEvent(aNE: TNotifyEvent); end; var Form1: TForm1; implementation {$R *.DFM} { TNotifyEventObj } constructor TNotifyEventObj.Create(aNE: TNotifyEvent); begin FNotifyEvent := aNE; end; { TForm1 } constructor TForm1.Create(AOwner: TComponent); begin inherited; FCount := 0; FLIst := TObjectList.Create; end; destructor TForm1.Destroy; begin FList.Free; inherited; end; procedure TForm1.Button1Click(Sender: TObject); begin AddEvent(CountEvent); end; procedure TForm1.Button2Click(Sender: TObject); var lNE: TNotifyEvent; I: Integer; begin for I := 0 to FList.Count - 1 do { Iterate } begin lNE := TNotifyEventObj(FList[I]).NotifyEvent; lNE(self); end; end; procedure TForm1.AddEvent(aNE: TNotifyEvent); begin FLIst.Add(TNotifyEventObj.Create(aNE)); end; procedure TForm1.CountEvent(Sender: TObject); begin FCount := FCount + 1; Caption := IntToStr(FCount); end; end. |