0

我正在制作一个库存系统,但我被困在应该通过简单的拖放操作将项目从一个单元格移动到另一个单元格的部分。

有一个Item[,] Inventory包含项目的数组,object fromCell, toCell它应该包含对单元格的引用,以便在释放鼠标按钮时进行操作,但是当我尝试这样做时:

object temp = toCell;
toCell = fromCell;
fromCell = temp;

...游戏只是交换对象引用,而不是实际对象。我该如何进行这项工作?

UPD:感谢 Bartosz,我明白了这一点。事实证明,您可以安全地使用对对象数组的引用,并使用您希望交换的对象的已保存索引来更改它。

代码可以是这样的:

object fromArray, toArray;
int fromX, fromY, toX, toY;

// this is where game things happen

void SwapMethod()
{
    object temp = ((object[,])toArray)[toX, toY];
    ((object[,])toArray)[toX, toY] = ((object[,])fromArray)[fromX, fromY];
    ((object[,])fromArray)[fromX, fromY] = temp;
}
4

2 回答 2

2

这个怎么样?

internal static void Swap<T>(ref T one, ref T two)
{
    T temp = two;
    two = one;
    one = temp;
}

你所有的交换都变成了这个。

Swap(Inventory[fromCell], Inventory[toCell]);

此外,您可以添加数组的扩展名(如果更舒适)。

public static void Swap(this Array a, int indexOne, int indexTwo)
{
    if (a == null)
        throw new NullReferenceException(...);

    if (indexOne < 0 | indexOne >= a.Length)
        throw new ArgumentOutOfRangeException(...);

    if (indexTwo < 0 | indexTwo >= a.Length)
        throw new ArgumentOutOfRangeException(...);

    Swap(a[indexOne], a[indexTwo]);
}

像这样使用它:

Inventory.Swap(fromCell, toCell);
于 2012-09-16T10:44:36.093 回答
1

为什么不使用Inventory数组索引:int fromCell, toCell.

var temp = Inventory[toCell];
Inventory[toCell] = fromCell;
Inventory[fromCell] = temp;

您将库存建模为 2D 插槽数组,因此使用索引访问它似乎相当安全。

于 2012-09-15T20:44:11.483 回答