簡體   English   中英

是否有可能在Delphi中對一個回調函數進行類型轉換?

[英]Is it possible to typecast a callback function in Delphi?

Delphi TList.Sort()方法需要一個類型為function (Item1, Item2: Pointer): Integer;的回調函數參數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 MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
  LHS: TMyType absolute Item1;
  RHS: TMyType absolute Item2;
begin
  result := WideCompareStr(LHS.Name, RHS.Name);
end;

可以進行類型轉換,但需要在函數名前加上“@”:

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

正如評論中所指出的,當關閉類型檢查指針時不需要類型轉換,因此在這種情況下,這也有效:

MyList.Sort(@MyTypeListSortCompare);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM