0

我正在尝试使用此代码交换 ArrayCollection 中的两个项目。

private function swapCollectionElements(collection:ArrayCollection, fromIndex:uint, toIndex:uint) : void 
{
    var curItem:Object = collection.getItemAt(fromIndex);
    var swapItem:Object = collection.getItemAt(toIndex);

    collection.setItemAt(curItem, toIndex);
    collection.setItemAt(swapItem, fromIndex);

    collection.refresh();
}

调试代码时,我可以看到 curItem 和 swapItem 是正确的对象,但是当我执行我的第一个 setItemAt 时,它会替换我想要的对象,但也会替换我不想要的对象。有什么想法吗?

4

1 回答 1

4

这是因为调用 getItemAt 来设置 curItem 和 swapItem 会导致引用 ArrayCollection 中的对象而不是对象本身。当您使用第一个 setItemAt 更改对象时,您的引用也会更改。此时 curItem 和 swapItem 可能都引用同一个对象。我会以不同的方式处理这个问题,并改用 removeItemAt 和 addItemAt,这样您就可以使用对象而不是引用。希望有帮助。

于 2010-10-11T21:50:09.923 回答