Creating an instance of a delegate and using it
The standard Delphi event syntax creates a single-cast event:
~~~~~~~~~~~~~~~~~~~~~~~~~
type
TSampleEventHandler = procedure(Sender: TObject; Args: EventArgs) ;
TWinForm18 = class(System.Windows.Forms.Form)
private
FMultiSampleEventHandler: TSampleEventHandler;
property MultiSampleEventHandler: TSampleEventHandler add FMultiSampleEventHandler remove FMultiSampleEventHandler;
end;
TWinForm18 = class(System.Windows.Forms.Form)
private
FSingleSampleEventHandler: TSampleEventHandler;
property SampleEventHandler: TSampleEventHandler read FSingleSampleEventHandler write FSingleSampleEventHandler;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
To create a multi-cast delegate, one must use the new keywords, add and remove:
~~~~~~~~~~~~~~~~~~~~~~~~~
type
TSampleEventHandler = procedure(Sender: TObject; Args: EventArgs) ;
TWinForm18 = class(System.Windows.Forms.Form)
private
FMultiSampleEventHandler: TSampleEventHandler;
property MultiSampleEventHandler: TSampleEventHandler add FMultiSampleEventHandler remove FMultiSampleEventHandler;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
As in standard Delphi property syntax, instead of simply referring to the field FMultiSampleEventHandler, one could refer to a method that does the actual add and remove operation and "roll out" the event. The implementation of the events is tricky if you dont know the syntax:
~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TWinForm18.AddMultiEvent(Value: TSampleEventHandler) ;
begin
FMultiSampleEventHandlerByHand := TSampleEventHandler(Delegate.Combine(@FMultiSampleEventHandlerByHand, @Value)) ;
end;
procedure TWinForm18.RemoveMultiEvent(Value: TSampleEventHandler) ;
begin
FMultiSampleEventHandlerByHand := TSampleEventHandler(Delegate.Remove(@FMultiSampleEventHandlerByHand, @Value)) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
Notice the use of @ to get the address of the event; if you dont use this, the compiler will think you are trying to call the event. Also notice the cast to the event type.
In Delphi, one can easily assign to a single-cast delegate and get traditional Delphi behavior:
~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TWinForm18.TWinForm18_Load(sender: System.Object; e: System.EventArgs) ;
begin
SampleEventHandler := OnSampleEvent;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
But, to add to a multi-case delegate, one must uses Include( ) :
~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TWinForm18.TWinForm18_Load(sender: System.Object; e: System.EventArgs) ;
begin
Include(MultiSampleEventHandler, OnSampleEvent) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
The way to remove an event from a multi-cast delegate is to use Exclude(). First, check to make sure it isnt null, and then call it like a method.
~~~~~~~~~~~~~~~~~~~~~~~~~
if Assigned(FSingleSampleEventHandler) then
FSingleSampleEventHandler(Self, EventArgs.Create) ;
~~~~~~~~~~~~~~~~~~~~~~~~~
Our discussion continues with a view on .Net Attributes ...

