Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi 如何使用匿名函数?_Delphi_Delphi Xe6 - Fatal编程技术网

Delphi 如何使用匿名函数?

Delphi 如何使用匿名函数?,delphi,delphi-xe6,Delphi,Delphi Xe6,如何正确使用匿名函数?我正在尝试使用一个通用的比较函数,但在下面的示例中出现以下错误。有人能解释为什么会这样吗 program Project11; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, System.Classes; type TSort<T> = record private type TCompare = reference to function(const L, R:

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

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.
程序项目11;
{$APPTYPE控制台}
{$R*.res}
使用
System.SysUtils,
系统、班级;
类型
t排序=记录
私有的
类型
T比较=对函数的引用(常数L,R:T):整数;
公众的
类过程排序(var A:T的数组;const First,Last:Integer;const Compare:TCompare);静止的
结束;
{TSort}
类过程TSort.Sort(变量A:T的数组;常量First,Last:Integer;常量Compare:TCompare);
变量
I:整数;
开始
I:=比较(1,2);//[dcc32错误]Project11.dpr(30):E2010不兼容类型:“T”和“Integer”
结束;
变量
A:整数数组;
开始
t排序(A,1,2,
函数(常量L,R:整数):整数
开始
//用L&R做点什么
(完),;
结束。

我认为你应该

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

而不是

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


事实上,你后来说你不想成为一个整数在这一点上是不相关的:如果你在这一点上说你的代码总是使用整数作为T,那么你不应该使用泛型

T将是任何东西,而不仅仅是一个整数。@user3764855这样认为(否则使用泛型就没有意义了)。因此在这种情况下,
Compare(1,2)
肯定是错误的。FWIW,
Generics.Collections中的
TArray.Sort
已经实现了这一点。还有,FWIW,你的比较功能不好。想象一下当
L
高(整数)
R
低(整数)时会发生什么
@DavidHeffernan compare函数可以是任何具有泛型之美的函数,而不需要任何类型的接口。您正在从
System.generics.Collections
System.generics.Defaults
中重新创造东西。您不需要处理任何接口。您可以只提供一个比较函数。我不认为你的比较函数很美。我称之为溢出发生器。您的整个代码可以替换为
TArray.Sort(A)
。如果您想提供比较函数,请使用
TArray.Sort(a,TComparer.Construct(Comparison))
其中
Comparison
是您的匿名方法。另外,+1表示具有完整代码和完整错误消息的非常好的SSCCE。
I := Compare(1, 2);