繁体   English   中英

结构变量不变

[英]Struct variables not changing

我觉得自己似乎遗漏了一些显而易见的东西,因此,如果是这样的话,我会提前道歉。 我正在尝试做一些非常简单的事情,将结构中的布尔值从false更改为true。 显然我不能直接更改它,因此我在可以调用的结构中创建了一个方法,该方法应该在那里更改值。 似乎并非如此。 这是代码,我将不胜感激。

public Dictionary<int, List<ScanLineNode>> allScanLineNodes = new Dictionary<int, List<ScanLineNode>>();

public void MethodName(ScanLineNode node [...])
{       
    //This will perform a raycast from the Node's position in the specified direction. If the raycast hits nothing, it will return Vector3.zero ('Row is complete'), otherwise will return the hit point

    Vector3 terminationPoint = node.RaycastDirection(node, direction, maxDist, targetRaycast, replacementColour, backgroundColour);

    ScanLineNode terminationNode = new ScanLineNode();

    //Previously attempted to store a local reference to this row being used, but also did not work
    //List<ScanLineNode> rowNodes = allScanLineNodes[node.rowNumber];

    [...]

    if (terminationPoint == Vector3.zero)
    {
        //Definitely reaches this point, and executes this function along the row, I have added breakpoints and checked what happens in this for loop. After running 'RowComplete' (which just changes 'rowComplete' from false to true) 'rowComplete' is still false. Just in case I've included the RowComplete() function below.

        Debug.Log("Row Complete: " + node.rowNumber);
        for (int i = 0; i < allScanLineNodes[node.rowNumber].Count; i++)
        {
            allScanLineNodes[node.rowNumber][i].RowCompleted();
        }
    }
}

ScanLineNode Struct-大多数东西都是隐藏的(我不认为会影响这一点),但是我包含了RowComplete()函数。

public struct ScanLineNode
    {
        [...]
        public bool rowComplete;
        [...]

        public ScanLineNode([...])
        {
            [...]
            rowComplete = false;
            [...]
        }

        public void RowCompleted()
        {
            rowComplete = true;
        }
    }

我还确认了在上述位置以外的任何地方都不会调用RowCOmpleted(),并且仅从RowComplete()函数中调用“ rowComplete”

(来自注释) allScanLineNodes is a Dictionary<int, List<ScanLineNode>>

对; List<ScanLineNode>的索引器返回该结构的副本 因此,当您调用该方法时-您是在堆栈上断开连接的值上调用它,此值稍后会蒸发(在堆栈上被覆盖-这不是垃圾收集器)。

这是可变结构的常见错误。 最好的选择可能是:不要构造可变的结构。 但是...您可以将其复制出来,对其进行变异,然后将变异的值推回:

var list = allScanLineNodes[node.rowNumber];
var val = list[i];
val.RowCompleted();
list[i] = val; // push value back in

但是不可变通常更可靠。

注意:您可以使用arrays 解决这个问题,因为数组中的索引器可以访问对就地结构的引用 -而不是值的副本 但是:这不是建议,因为依靠这种细微的差异会引起混乱和错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM