应恢弘之约,写了一个对其发布的匿名函数动态绑定到事件的封装,代码如下:

type
TAnonEvent=class
public
class function Wrap<T1,T2>(OnEvent:T1):T2;
end;
{ TAnonEvent }
class function TAnonEvent.Wrap<T1,T2>(OnEvent: T1):T2;
var
Addr:Pointer;
AMethod:PMethod;
begin
Addr:=PPointer(@OnEvent)^;
AMethod:=@Result;
AMethod.Code:=PPointer(IntPtr(PPointer(Addr)^)+SizeOf(Pointer)*3)^;//QueryInterface/AddRef/Release/Invoke
AMethod.Data:=Pointer(Addr);
end;

type
TNotifyEventA=reference to procedure(ASender:TObject);
procedure TForm3.Button1Click(Sender: TObject);
begin
Button2.OnClick:=TAnonEvent.Wrap<TNotifyEventA,TNotifyEvent>(procedure (sender: tObject)
begin
Button2.Caption:=DateTimeToStr(Now);
ShowMessage('OK');
end);
Button2.OnClick(Sender);
end;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type
  TAnonEvent=class
  public
    class function Wrap<T1,T2>(OnEvent:T1):T2;
  end;
{ TAnonEvent }
class function TAnonEvent.Wrap<T1,T2>(OnEvent: T1):T2;
var
  Addr:Pointer;
  AMethod:PMethod;
begin
Addr:=PPointer(@OnEvent)^;
AMethod:=@Result;
AMethod.Code:=PPointer(IntPtr(PPointer(Addr)^)+SizeOf(Pointer)*3)^;//QueryInterface/AddRef/Release/Invoke
AMethod.Data:=Pointer(Addr);
end;
 
type
  TNotifyEventA=reference to procedure(ASender:TObject);
procedure TForm3.Button1Click(Sender: TObject);
begin
Button2.OnClick:=TAnonEvent.Wrap<TNotifyEventA,TNotifyEvent>(procedure (sender: tObject)
     begin
      Button2.Caption:=DateTimeToStr(Now);
       ShowMessage('OK');
     end);
Button2.OnClick(Sender);
end;

【注意】

由于匿名函数中,我将TMethod.Data指向了匿名函数对应的接口对象,所以在匿名函数中,不要使用Self来代表当前对象。如果非要使用的话,那么自己修改下Wrap的代码,将AMethod.Data:=Pointer(Addr)改为指向当前函数所隶属对象的Self即可。

原创文章转载请注明:转载自:Delphi中匿名方法动态绑定事件

最新文章

  1. ViewController生命周期
  2. ASCII表
  3. C#中XmlTextWriter读写xml文件详细介绍(转)
  4. 【翻译六】java-连接和实例
  5. &lt;marquee&gt;属性详解
  6. CorelDRAW 二维码插件
  7. Log4j 2.0 使用说明
  8. Oracle Minus 取差集
  9. oracle的concat的用法
  10. 页面提交错误,页面间参数传递java.lang.NumberFormatException: null
  11. HDU - 3853
  12. JAVA 验证码生成(转)
  13. set排序(个人模版)
  14. COPD——团队项目测试心得
  15. webstorm基础使用
  16. ASP.NET MVC 网站优化之压缩技术
  17. 洛谷 P4779 【dijkstra】+(堆优化)+(链式前向星) (模板题)
  18. 微信小程序开发——小程序API获取用户位置及异常流处理完整示例
  19. 20165315 预备作业3 Linux安装及学习
  20. sqlhelper中事务的简单用法

热门文章

  1. swift的static和class修饰符---What is the difference between static func and class func in Swift?
  2. du - 报告磁盘空间使用情况
  3. 前端拖动div 效果
  4. JavaScript设计模式基础之this、call、apply
  5. mysql中使用load data infile导入数据的用法
  6. htmlpurifier的使用
  7. 初识Pyhon
  8. JSTL标签判断list是否为空
  9. 【HDU 1402】A * B Problem Plus(FFT)
  10. shelve -- 用来持久化任意的Python对象