【发布时间】:2011-12-10 04:45:07
【问题描述】:
我正在尝试使用 C# 中的 ref 关键字来修改传递给委托函数的类变量。我希望委托函数能够修改存储在容器中的父级及其两个子级的值。现在发生的情况是委托函数可以修改父函数(因为我直接将引用传递给容器 [parent])但不能修改子函数,因为我必须先处理它们并因此传递对 leftChild 和 rightChild 的引用。
-
是否可以让leftChild 成为对容器[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); } }
【问题讨论】: