Home > Mobile >  How to assign an "of object" procedure to a "reference to" procedure?
How to assign an "of object" procedure to a "reference to" procedure?

Time:12-02

I have :

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

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

and

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

I want to do something like

   MyObject.MyProc := AnObject.MyProcImpl;

but I get Incompatible types: 'TMyProc' and 'Procedure of object'. How can I do ?

CodePudding user response:

The problem is the ambiguity introduced by the overloads. Without the overloads your code would work fine.

You can disambiguate the overloads by using a temporary variable that is typed to match the overload you want to 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.

Another way to resolve this is to write out the anonymous method explicitly instead of relying on the compiler to generate it behind the scenes:

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