加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何将方法类型作为参数传递?

发布时间:2020-12-15 09:15:27 所属栏目:大数据 来源:网络整理
导读:我想传递事件类型,如TNotifyEvent或TKeyPressEvent. 如何声明方法参数来接受这些类型? procedure RegisterEventType(AEventType: ???) 这样编译: RegisterEventType(TNotifyEvent)RegisterEventType(TKeyPressEvent) 指出TKeyPressEvent和TNotifyEvent明显
我想传递事件类型,如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.

解决方法

像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>(...);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读