我正在尝试使用 C# 中的 ref 关键字来修改传递给委托函数的类变量。我希望委托函数能够修改存储在容器中的父级及其两个子级的值。现在发生的事情是委托函数可以修改父函数(因为我将引用直接传递给容器 [parent])但不能修改子函数,因为我必须先处理它们,从而传递对 leftChild 和 rightChild 的引用。
是否可以让 leftChild 成为对 container[leftChildIndex] 的引用,以便委托函数可以修改存储在容器中的值?(与右孩子相同)
private void traversePostOrder(Modify operation, int parentIndex) { if (parentIndex < size) { int leftChildIndex = getLeftChildIndex(parentIndex); int rightChildIndex = getRightChildIndex(parentIndex); T parent = container[parentIndex]; T leftChild = default(T); T rightChild = default(T); Library.Diagnostics.Message.logMessage("P: " + parent, 2); if (leftChildIndex < container.Length) { traversePostOrder(operation, leftChildIndex); leftChild = container[leftChildIndex]; } if (rightChildIndex < container.Length) { traversePostOrder(operation, rightChildIndex); rightChild = container[rightChildIndex]; } operation(ref container[parentIndex], ref leftChild, ref rightChild); } }