这是我的代码示例:
type
TMyBaseClass = class
public
procedure SomeProc; virtual;
end;
TMyChildClass = class(TMyBaseClass)
public
procedure SomeProc; override;
end;
var
SomeDelegate: procedure of object;
procedure TMyBaseClass.SomeProc;
begin
ShowMessage('Base proc');
end;
procedure TMyChildClass.SomeProc;
begin
ShowMessage('Child proc');
// here i want to get a pointer to TMyBaseClass.SomeProc (NOT IN THIS CLASS!):
SomeDelegate := SomeProc;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
with TMyChildClass.Create do
try
// there will be "Child proc" message:
SomeProc;
finally
Free;
end;
// there i want to get "Base proc" message, but i get "Child proc" again
// (but it is destroyed anyway, how coud it be?):
SomeDelegate;
end;
Run Code Online (Sandbox Code Playgroud)
我知道的一种方式是:
procedure TMyChildClass.BaseSomeProc;
begin
inherited SomeProc;
end;
procedure TMyChildClass.SomeProc;
begin
ShowMessage('Child proc');
SomeDelegate := BaseSomeProc;
end;
Run Code Online (Sandbox Code Playgroud)
第二是将SomeProc声明override改为reintroduce:
TMyChildClass = class(TMyBaseClass)
public
procedure SomeProc; reintroduce;
end;
Run Code Online (Sandbox Code Playgroud)
然后施放self为TMyBaseClass(不要使用as演员表):
SomeDelegate := TMyBaseClass(self).SomeProc;
Run Code Online (Sandbox Code Playgroud)
另请注意,您的代码将提供访问冲突,因为您调用SomeDelegate已释放的对象.
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |