当前位置 : 主页 > 编程语言 > delphi >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
这是我的代码示例: type TMyBaseClass = class public procedure SomeProc; virtual; end; TMyChildClass = class(TMyBaseClass) public procedure SomeProc; override; end;var SomeDelegate: procedure of object;procedure TMyBaseClass.SomePro
这是我的代码示例:

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;
我知道的一种方式是:

procedure TMyChildClass.BaseSomeProc;
begin
  inherited SomeProc;
end;


procedure TMyChildClass.SomeProc;
begin
  ShowMessage('Child proc');
  SomeDelegate := BaseSomeProc;
end;

第二个是将SomeProc声明从覆盖更改为重新引入:

TMyChildClass = class(TMyBaseClass)
 public
    procedure SomeProc; reintroduce;
 end;

然后将self转换为TMyBaseClass(不要使用as cast):

SomeDelegate := TMyBaseClass(self).SomeProc;

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

网友评论