我想传递事件类型,例如TNotifyEvent或TKeyPressEvent。
如何声明方法参数以接受这些类型?
procedure RegisterEventType(AEventType: ???)
这样编译:
RegisterEventType(TNotifyEvent)
RegisterEventType(TKeyPressEvent)
指出TKeyPressEvent
和TNotifyEvent
明显不同:
TNotifyEvent = procedure(Sender: TObject) of object;
TKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object;
所以它不是我要传递的事件实例,而是它的类型。
为了给出一些上下文,这是实现:
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创建一个实现TNotifyEvent的IEventRedirect实例,用于重定向表单上的事件处理程序。每种支持的事件类型都有一个实现(TNotifyEvent,TKeyPressEvent ...)。 这允许集中记录和测量在事件处理程序中包含大量代码的表单。
因此,目的是不传递字符串'TNotifyEvent'
,而是传递实际类型TNotifyEvent
。
答案 0 :(得分:3)
像hvd建议的那样,如果您的Delphi版本支持,可以使用Generics,例如:
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>(...);