3

如何正确使用匿名函数?我正在尝试使用通用比较函数,但在下面的示例中出现以下错误。有人可以解释为什么会这样吗?

program Project11;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.Classes;

type
  TSort<T> = record
  private
    type
      TCompare = reference to function(const L, R: T): Integer;
  public
    class procedure Sort(var A: Array of T; const First, Last: Integer; const Compare: TCompare); static;
  end;

{ TSort<T> }

class procedure TSort<T>.Sort(var A: array of T; const First, Last: Integer; const Compare: TCompare);
var
  I: Integer;
begin
  I := Compare(1, 2); // [dcc32 Error] Project11.dpr(30): E2010 Incompatible types: 'T' and 'Integer'
end;

var
  A: Array of Integer;
begin
  TSort<Integer>.Sort(A, 1, 2,
  function(const L, R: Integer): Integer
  begin
    // Do something with L & R
  end);
end.
4

1 回答 1

2

我认为你实际上应该想要

I := Compare(A[1], A[2]);

或者

I := Compare(A[First], A[Last]);

代替

I := Compare(1, 2);

正如 TLama 已经提到的:Compare 需要两个 T 类型的参数。A 是 T 的数组,因此您可以提供其成员。然而,1 和 2 是整数。

您稍后说您希望 T 成为整数的事实在这一点上并不相关:如果您此时可以说您的代码总是将整数用作 T,那么您不应该使用泛型

于 2014-06-25T12:34:06.483 回答