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

时间:2018-03-21 15:01:07

标签: function delphi casting delphi-2006

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)中正确地对类型指针进行类型转换?

2 个答案:

答案 0 :(得分:6)

我通常会这样做:

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

答案 1 :(得分:3)

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

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

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

MyList.Sort(@MyTypeListSortCompare);