Function 可以在Delphi中键入回调函数吗?

Function 可以在Delphi中键入回调函数吗?,function,delphi,casting,delphi-2006,Function,Delphi,Casting,Delphi 2006,DelphiTList.Sort()方法需要类型为function(Item1,Item2:Pointer:Integer)的回调函数参数用于比较列表项 我想摆脱回调函数中的类型转换,并定义如下回调函数: function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer; begin result := WideCompareStr(Item1.Name, Item2.Name); end; ... MyList.Sor

Delphi
TList.Sort()
方法需要类型为
function(Item1,Item2:Pointer:Integer)的回调函数参数用于比较列表项

我想摆脱回调函数中的类型转换,并定义如下回调函数:

function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer;
begin
   result := WideCompareStr(Item1.Name, Item2.Name);
end;

...
MyList.Sort(tListSortCompare(MyTypeListSortCompare));
...
function MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
  LHS: TMyType absolute Item1;
  RHS: TMyType absolute Item2;
begin
  result := WideCompareStr(LHS.Name, RHS.Name);
end;
但不幸的是,这会触发“无效类型转换”编译器错误


是否有可能在Delphi(2006)中正确地类型转换函数指针?

类型转换是可能的,但需要在函数名前面加上“@”:

正如注释中指出的,当类型检查指针被关闭时,不需要类型转换,因此在这种情况下,这也可以工作:

MyList.Sort(@MyTypeListSortCompare);

我通常会这样做:

function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer;
begin
   result := WideCompareStr(Item1.Name, Item2.Name);
end;

...
MyList.Sort(tListSortCompare(MyTypeListSortCompare));
...
function MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
  LHS: TMyType absolute Item1;
  RHS: TMyType absolute Item2;
begin
  result := WideCompareStr(LHS.Name, RHS.Name);
end;

不,那是不可能的。传递给该回调的Typecast项(回调必须与其声明匹配)。当然不是。但这样做毫无意义。您只编写了一次排序过程代码,而从不自己调用它。为什么您希望通过添加函数的hackish类型转换来增加读取和维护的难度?我使用排序回调作为示例,我的问题不限于排序。不需要转换<代码>MyList.Sort(@MyTypeListSortCompare)工作正常“实际上不需要类型转换”-只有在关闭时才需要,否则就需要。我必须问一下,
LHS
RHS
代表什么
L
R
是清楚的,但那
HS
?只是好奇:)顺便说一句。简单的类型转换,比如
WideCompareStr(TMyType(Item1.Name),TMyType(Item2.Name)在这里也会做同样的工作。@Victoria我猜是左手边和右手边Side@Victoria但是功能有点重,我左手里的东西比右手里的东西重,有点;)@Tom,
LHS
RHS
来自数学,但最终命名还不错。我使用
A
B
甚至用于回调参数(而不是
1
2
后缀)。@TomBrunberg左手边和右手边都是正确的。我不喜欢单字符变量名,所以L和R都不适用。左侧和右侧比左侧和右侧短:-)