问题-MethodAddress返回NIL?MethodAddress与published的关系?

问题现象:有位朋友(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 type
10   TTest = procedure of object;
11   TForm2 = class(TForm)
12     Button1: TButton;
13     procedure Button1Click(Sender: TObject);
14   private
15     { Private declarations }
16   public
17   published//使用MethodAddress必须定义在发布区的方法
18     procedure Test;
19     { Public declarations }
20   end;
21 
22 var
23   Form2: TForm2;
24 
25 implementation
26 
27 {$R *.dfm}
28 
29 procedure TForm2.Button1Click(Sender: TObject);
30 var
31   oP: TMethod;
32   otest: Ttest;
33 begin
34   oP.Data := Pointer(Self);
35   op.Code := Self.MethodAddress('Test');//使用MethodAddress必须定义在published(发布区)的方法
36 //  op.Code := @TForm2.test; //什么方法都可以返回地址
37   if Assigned(op.Code) then
38   begin
39     otest := Ttest(op);
40     otest;
41   end;    
42 end;
43 
44 procedure TForm2.Test;
45 begin
46   ShowMessage('Test');
47 end;
48 
49 end.
View Code
原文地址:https://www.cnblogs.com/FKdelphi/p/7602781.html