这里是我的代码示例:如何从Delphi中的子类获取指向基类中方法的指针?
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;
谢谢!你的第一种方法正是我想要的=) – SomeOne 2010-09-24 06:23:16
请注意Michal Niklas对违反访问权限的说法。你仍然会得到一个,即使是“继承”。这是因为你不能有一个指向CLASS方法的指针(除非它被声明为“class procedure”),只能用于OBJECT的方法。当你调用Free()时,你的对象被销毁,并且任何对它的引用,包括SomeDelegate(包含对它的函数的引用)都不再有效。 – himself 2010-09-24 11:54:13
当我尝试使用我的Turbo Delphi代码时,出现访问冲突异常。 – 2010-09-24 12:09:36