是否有可能在Delphi中对一个回调函数进行类型转换?

问题描述 投票:2回答:2

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));
...

但不幸的是,这会触发“无效的类型转换”编译器错误。

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

function delphi casting delphi-2006
2个回答
6
投票

我通常做这样的事情:

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

3
投票

可以进行类型转换,但需要在函数名前加上“@”:

var
   MyList : TList;
begin
   ...
   MyList.Sort(TListSortCompare(@MyTypeListSortCompare));
   ...
end;

正如评论中所指出的,当关闭类型检查指针时不需要类型转换,因此在这种情况下,这也有效:

MyList.Sort(@MyTypeListSortCompare);
© www.soinside.com 2019 - 2024. All rights reserved.