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

ble*_*tin 2 delphi casting function 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));
...
Run Code Online (Sandbox Code Playgroud)

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

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

Kei*_*ler 6

我通常做这样的事情:

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

  • @Victoria我猜左手侧和右手侧 (2认同)