如何在C#中使用ref修改此类变量?

时间:2011-10-18 15:00:42

标签: c# delegates ref

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

2 个答案:

答案 0 :(得分: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));
        }
    }
}

答案 1 :(得分:1)

你正在寻找的是指针,C#不会暴露它们 - 幸运的是。

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

operation(ref container[parentIndex], ref leftChild, ref rightChild);
container[leftChildIndex] = leftChild;
container[rightChildIndex] = rightChild;