如何将重载的类方法分配给匿名方法?

14
在Delphi中,我们可以将一个被声明为procedure of object的类方法作为匿名方法类型的参数进行赋值。对于重载方法(相同的方法名称),传递对象方法会导致编译错误:
[dcc32 Error] Project56.dpr(40): E2010 Incompatible types: 'System.SysUtils.TProc<System.Integer,System.Integer>' and 'Procedure of object'
下面的例子展示了这种情况。是否可以让重载的方法作为匿名方法参数传递?
Translated: The following example shows the situation. Is it possible to pass an overloaded method as an anonymous method parameter?
type
  TTest = class
  public
    procedure M(a: Integer); overload;
    procedure M(a, b: Integer); overload;
  end;

procedure TTest.M(a, b: Integer);
begin
  WriteLn(a, b);
end;

procedure TTest.M(a: Integer);
begin
  WriteLn(a);
end;

procedure DoTask1(Proc: TProc<Integer>);
begin
  Proc(100);
end;

procedure DoTask2(Proc: TProc<Integer,Integer>);
begin
  Proc(100, 200);
end;

begin
  var o := TTest.Create;
  DoTask1(o.M);  // <-- Success
  DoTask2(o.M);  // <-- Fail to compile: E2010 Incompatible types: 'System.SysUtils.TProc<System.Integer,System.Integer>' and 'Procedure of object'
  ReadLn;
end.
1个回答

17

当你写作时

DoTask2(o.M);
编译器看到 o.M 不是匿名方法,会在后台为您生成一个包装调用 o.M 的方法。不幸的是,在执行此操作时,编译器无法搜索重载方法,因此出现编译错误。

解决方案是手动生成匿名方法包装器。

DoTask2(
  procedure(a, b: Integer) 
  begin
    o.M(a, b);
  end 
);

当编译器用匿名方法包装标准方法时,这正是它在幕后为您执行的操作。因此,虽然语法令人疲倦,但最终结果在运行时是相同的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接