如何将 "of object" 过程分配给 "reference to" 过程?

How to assign an "of object" procedure to a "reference to" procedure?

我有:

  TMyProc = reference to procedure(const adata: String);

  TMyObject = Class(Tobject)
  private
    FMyProc: TMyProc ;
  public
    Property MyProc: TMyProc read FMyProc write FMyProc;
  end;

  TAnObject = Class(Tobject)
  public
    procedure MyProcImpl(const adata: integer); overload;
    procedure MyProcImpl(const adata: String); overload;
  end;

我想做类似的事情

   MyObject.MyProc := AnObject.MyProcImpl;

但我得到 Incompatible types: 'TMyProc' and 'Procedure of object'。我该怎么办?

问题是重载引入的歧义。如果没有重载,您的代码将可以正常工作。

您可以使用一个临时变量来消除重载的歧义,该变量的类型与您想要的重载相匹配 select:

program SO70183946;

type
  TMyProc = reference to procedure(const adata: string);
  TMyProcOfObject = procedure(const adata: string) of object;

  TMyObject = class
  private
    FMyProc: TMyProc;
  public
    property MyProc: TMyProc read FMyProc write FMyProc;
  end;

  TAnObject = class
  public
    procedure MyProcImpl(const adata: integer); overload;
    procedure MyProcImpl(const adata: string); overload;
  end;

procedure TAnObject.MyProcImpl(const adata: integer);
begin
end;

procedure TAnObject.MyProcImpl(const adata: string);
begin
end;

var
  MyObject: TMyObject;
  AnObject: TAnObject;
  MyProcOfObject: TMyProcOfObject;

begin
  MyProcOfObject := AnObject.MyProcImpl;
  MyObject.MyProc := MyProcOfObject;
end.

解决这个问题的另一种方法是显式写出匿名方法,而不是依赖编译器在幕后生成它:

MyObject.MyProc :=
  procedure(const adata: string)
  begin
    AnObject.MyProcImpl(adata);
  end;