如何从Delphi中的子类获取指向基类中方法的指针?

Som*_*One 3 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;
Run Code Online (Sandbox Code Playgroud)

Mic*_*las 8

我知道的一种方式是:

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)

然后施放selfTMyBaseClass(不要使用as演员表):

 SomeDelegate := TMyBaseClass(self).SomeProc;
Run Code Online (Sandbox Code Playgroud)

另请注意,您的代码将提供访问冲突,因为您调用SomeDelegate已释放的对象.