问题现象:有位朋友(397085381)在Q群里问“为什么书上的可以访问,而自己写的代码访问时为nil”
问题原因:因为要用“Self.MethodAddress('Test')”访问,方法必须放在“published”下。
问题处理:增加“published”就好了。
解答人员:541011510、316405484、397085381。
实例代码:
1 unit Unit2; 2 3 interface 4 5 uses 6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 7 Dialogs, StdCtrls; 8 9 type10 TTest = procedure of object;11 TForm2 = class(TForm)12 Button1: TButton;13 procedure Button1Click(Sender: TObject);14 private15 { Private declarations }16 public17 published//使用MethodAddress必须定义在发布区的方法18 procedure Test;19 { Public declarations }20 end;21 22 var23 Form2: TForm2;24 25 implementation26 27 { $R *.dfm}28 29 procedure TForm2.Button1Click(Sender: TObject);30 var31 oP: TMethod;32 otest: Ttest;33 begin34 oP.Data := Pointer(Self);35 op.Code := Self.MethodAddress('Test');//使用MethodAddress必须定义在published(发布区)的方法36 // op.Code := @TForm2.test; //什么方法都可以返回地址37 if Assigned(op.Code) then38 begin39 otest := Ttest(op);40 otest;41 end; 42 end;43 44 procedure TForm2.Test;45 begin46 ShowMessage('Test');47 end;48 49 end.