0

我正在尝试使用 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);
        }
    }
    
4

2 回答 2

1

问题是你在哪里定义它们:

T leftChild = default(T);
T rightChild = default(T);

您传递对这些对象的引用,它们在方法结束后立即被销毁,因为它们是局部变量。
尝试直接发送对象。

private void traversePostOrder(Modify operation, int parentIndex) {
    if (parentIndex < size) {
        int leftChildIndex = getLeftChildIndex(parentIndex);
        int rightChildIndex = getRightChildIndex(parentIndex);
        T parent = container[parentIndex];
        bool leftChildModified = false;
        bool rightChildModified = false;

        Library.Diagnostics.Message.logMessage("P: " + parent, 2);

        if (leftChildIndex < container.Length) {
            traversePostOrder(operation, leftChildIndex);
            leftChildModified = true;
        }

        if (rightChildIndex < container.Length) {
            traversePostOrder(operation, rightChildIndex);
            rightChildModified = true;
        }

        if(leftChildModified && rightChildModified)
        {
            operation(ref container[parentIndex], ref container[leftChildIndex], ref container[rightChildIndex]);
        }
        else if(leftChildModified)
        {
            operation(ref container[parentIndex], ref container[leftChildIndex], ref Default(T));
        }
        else if(rightChildModified)
        {
            operation(ref container[parentIndex], ref Default(T), ref container[rightChildIndex]);
        }
        else
        {
            operation(ref container[parentIndex], ref default(T), ref default(T));
        }
    }
}
于 2011-10-18T15:05:33.473 回答
1

您正在寻找的是指针,而 C# 并没有公开它们 - 幸运的是。

您可以简单地将值分配回类变量:

operation(ref container[parentIndex], ref leftChild, ref rightChild);
container[leftChildIndex] = leftChild;
container[rightChildIndex] = rightChild;
于 2011-10-18T15:11:18.707 回答