作为参数传递的函数会导致E2035错误

时间:2015-10-05 20:58:18

标签: delphi

在一个文件中,我有一段代码如下:

// foo.pas
unit Foo;

type
FooExecutorMethod = function (param: Pointer) : Integer of Object;

FooExecutor = class
private
  FMethod: TiTefExecutorMethod;
  FMethodParam: Pointer;
  FMethodResult: Integer;
public
  function RunMethod(method: TiTefExecutorMethod; param: Pointer) : Integer;
end;

implementation

function FooExecutor.RunMethod(method: FooExecutorMethod; param: Pointer) : Integer;
begin
  FMethod:= method; // Never gets assigned :(
  FMethodParam:= param;

  // Some threading logic here.  
end;

在同一个项目的另一个文件中,我得到了这样的内容:

// bar.pas
uses Foo;

type
bar = class
protected
  executor: FooExecutor;
  function doSomething(params: Pointer): Integer;
  Constructor Create(params: Pointer);

implementation

Function bar.doSomething(params: Pointer) : Integer;
begin
    // Do something with the pointer
    Result := 1;
end;

Constructor bar.Create(params: Pointer)
var
  r: Integer;
begin
  executor := FooExecutor.Create
  r := executor.RunMethod(doSomething, params);
end;

问题是,bar.DoSomething永远不会被执行。在调试FooExecutor.RunMethod时,评估者不会显示其" method"的值。参数 - 它显示以下内容:

  

E2035实际参数不足

因此我无法使用对bar.DoSomething的引用。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

永远不会执行该方法,因为您从不调用它。你所做的就是传递对方法的引用。但你永远不会称之为。

你会这样称呼:

function FooExecutor.RunMethod(method: FooExecutorMethod; param: Pointer): Integer;
begin
  Result := method(param);
end;

显然,您的代码正在尝试执行其他操作,但这是调用该方法的方法。