【发布时间】:2012-01-08 04:20:43
【问题描述】:
我正在尝试实现 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;
我相当肯定这在运行时必须是可能的,因为它在设计时由 Delphi IDE 本身完成,它提供了一种对列表中的集合项重新排序的方法。我希望通过简单地重新排序现有对象来做到这一点,而无需创建、销毁或分配任何对象。这可能来自 Classes.pas TCollection 的子类吗? (如果没有,我可能必须从源克隆制作自己的 TCollection)
【问题讨论】:
-
设置集合项的
Index属性应该做Item.Index:=Item.Index+1(这会调用集合项列表的Move)。如果需要任何特殊处理,SetIndex方法将被覆盖。
标签: delphi tcollection tcollectionitem