How to pass a method type as a parameter?

I would like to pass event types like TNotifyEvent or TKeyPressEvent.

How to declare a param method to accept these types?

procedure RegisterEventType(AEventType: ???)

so that these compilations:

RegisterEventType(TNotifyEvent)
RegisterEventType(TKeyPressEvent)

The point of that TKeyPressEventand TNotifyEvent, obviously different:

TNotifyEvent = procedure(Sender: TObject) of object;
TKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object;

So this is not an instance of the event that I want to pass, it is a type.

To give some context, this is an implementation:

procedure RegisterEventType(AEventType: ???; AFactory: TRedirectFactory)
var
  vTypeInfo: PTypeInfo;
begin
  vTypeInfo := TypeInfo(AEventType);
  Assert(vTypeInfo.Kind = tkMethod);
  vTypeInfo.Name <------ contains string 'TNotifyEvent'

  SetLength(fFactories, Length(fFactories)+1);
  fFactories[High(fFactories)].EventType := vTypeInfo.Name;
  fFactories[High(fFactories)].Factory := AFactory;
end;

context: TRedirectFactory creates an instance of IEventRedirect that implements TNotifyEvent and is used to redirect event handlers to forms. There is one implementation for each supported event type (TNotifyEvent, TKeyPressEvent ...). This allows you to centrally register and measure forms that have a lot of code in event handlers.

, , 'TNotifyEvent', TNotifyEvent.

+4
1

hvd, Generics, Delphi , :

type
  TEventTypeRegistrar<T> = class
  public
    class procedure Register(AFactory: TRedirectFactory);
  end;

class procedure TEventTypeRegistrar<T>.Register(AFactory: TRedirectFactory);
var
  vTypeInfo: PTypeInfo;
begin
  vTypeInfo := TypeInfo(T);
  Assert(vTypeInfo.Kind = tkMethod);

  SetLength(fFactories, Length(fFactories)+1);
  fFactories[High(fFactories)].EventType := vTypeInfo.Name;
  fFactories[High(fFactories)].Factory := AFactory;
end;

TEventTypeRegistrar<TNotifyEvent>.Register(...);
TEventTypeRegistrar<TKeyPressEvent>.Register(...);

:

type
  TEventTypeRegistrar = class
  public
    class procedure Register<T>(AFactory: TRedirectFactory);
  end;

class procedure TEventTypeRegistrar.Register<T>(AFactory: TRedirectFactory);
var
  vTypeInfo: PTypeInfo;
begin
  vTypeInfo := TypeInfo(T);
  Assert(vTypeInfo.Kind = tkMethod);

  SetLength(fFactories, Length(fFactories)+1);
  fFactories[High(fFactories)].EventType := vTypeInfo.Name;
  fFactories[High(fFactories)].Factory := AFactory;
end;

TEventTypeRegistrar.Register<TNotifyEvent>(...);
TEventTypeRegistrar.Register<TKeyPressEvent>(...);
+3

All Articles