如何重新排序TCollection中的项目?

War*_* P 4 delphi tcollection tcollectionitem

我正在尝试实现MoveItemUp和MoveItemDown方法,这些方法在一个索引中向上或向下移动选定的行TCollection.

以下代码添加到我的TCollection子类中不起作用:

procedure TMyCollection.MoveRowDown(index: Integer);
var
 item:TCollectionItem;
begin
  if index>=Count-1 then exit;
  item := Self.Items[index];
  Self.Delete(index); // whoops this destroys the item above.
  Self.Insert(index+1);
  Self.SetItem(index+1,item); // this actually does an assign from a destroyed object.
end;
Run Code Online (Sandbox Code Playgroud)

我很确定这必须在运行时可行,因为它在设计时由Delphi IDE本身完成,它提供了一种重新排序列表中的Collection项的方法.我希望通过简单地重新排序现有对象来实现这一点,而无需创建,销毁或分配任何对象.这可能来自Classes.pas TCollection的子类吗?(如果没有,我可能必须从源克隆创建我自己的TCollection)

Pat*_*man 9

根据VCL来源,您无需手动执行此操作.只需设置Index像@Sertac建议的属性,它应该工作得很好.如果您有源代码,请查看代码TCollectionItem.SetIndex.

  • 谢谢Sertac.这个答案基本上复制了你的想法,但是作为答案发布了. (2认同)