gpt4 book ai didi

c# - 如何在保存数组的类之外引用数组元素?

转载 作者:行者123 更新时间:2023-11-30 22:24:19 24 4
gpt4 key购买 nike

我在一个类中有一个类数组(Voxel)。我使用以下方法在数组中添加和删除。备忘录模式用于存储每个方法的操作,因此可以随时撤消/重做。

    public void AddVoxel(int x, int y, int z)
{
int index = z * width * height + y * width + x;

frames[currentFrame].Voxels[index] = new Voxel();

// Undo/Redo history
undoRedoHistories[currentFrame].Do(new AddMemento(index));
}

public void RemoveVoxel(int x, int y, int z)
{
int index = z * width * height + y * width + x;

// Undo/Redo history
undoRedoHistories[currentFrame].Do(new RemoveMemento(index, frames[currentFrame].Voxels[index]));

frames[currentFrame].Voxels[index] = null; // Does not update 'voxelSelected' reference
}

在一个单独的类中,我希望引用上述类持有的体素数组中的特定体素。

private Voxel voxelSelected = null;

作为引用类型,我希望这个值能够自动知道它“指向”的数组部分何时包含体素或为空。这在使用撤消命令时很重要,因为体素可以从数组中删除并变为空,反之亦然。

要从数组中获取体素,我使用以下方法。

public Voxel GetVoxel(int x, int y, int z)
{
return frames[currentFrame].Voxels[z * width * height + y * width + x];
}

然后我按如下方式设置对体素的引用。

public void SetVoxelSelected(ref Voxel voxel)
{
voxelSelected = voxel;
}

voxelMeshEditor.AddVoxel(0, 0, 0);

var voxel = voxelMeshEditor.GetVoxel(0, 0, 0); // Copies rather than references?

SetVoxelSelected(ref voxel);

Console.WriteLine(voxelSelected == null); // False

voxelMeshEditor.RemoveVoxel(0, 0, 0);

Console.WriteLine(voxelSelected == null); // False (Incorrect intended behaviour)

如何正确引用数组中的体素,以便 voxelSelected 值在数组更新时自动更新。

最佳答案

How can I correctly reference a voxel in the array so the voxelSelected value automatically updates when the array updates.

不存储体素,而是存储获取体素所需的坐标。

代替

Voxel voxelSelected;
public void SetVoxelSelected(ref Voxel voxel) { voxelSelected = voxel; }

int selectedX, selectedY, selectedZ
public void SetVoxelSelected (int x, int y, int z) { selectedX = x; ... }
public Voxel GetVoxelSelected() { return voxelMeshEditor.GetVoxel(x, y, z) }

给予

SetVoxelSelected(0, 0, 0);                     //Set selected
Console.WriteLine(GetVoxelSelected() == null); // False, CORRECT !
voxelMeshEditor.RemoveVoxel(0, 0, 0); //REMOVE
Console.WriteLine(GetVoxelSelected() == null); // True

关于c# - 如何在保存数组的类之外引用数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12818677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com