分配给引用类型参数

时间:2018-06-20 23:07:34

标签: c#

我正在实现二叉树,并且在理解引用类型时遇到了一些问题。

这不是实现本身,而是一段使我困惑的代码。

class SomeType { }
class BinaryTree
{
    public SomeType root = null;

    public void Add(SomeType something)
    {
        Insert(root, something);
    }

    private void Insert(SomeType current, SomeType newItem)
    {
        if(current == null)
            current = newItem;
    }

}

以及用法

void Main()
{
    DataStructure ds = new DataStructure();
    ds.Add(new SomeType());
    Console.WriteLine(ds.root);
}

哪个产生null来进行控制台。

问题是,当我调用Insert方法时,传递root作为引用,然后分配给current新对象时,我希望它出现在{{1}下}字段,因为我通过了引用,对不对?但是相反,我在root下得到了null

我的理解有什么问题?

1 个答案:

答案 0 :(得分:0)

引用类型的变量不直接包含其数据。它包含对其数据的引用。当按值传递引用类型参数时,可以更改属于被引用对象的数据,例如类成员的值。 但是,您不能更改引用本身的值;例如,您不能使用相同的引用来为新类分配内存,并使该内存持久化到方法之外。为此,请使用refout关键字传递参数。

文档:Passing Reference-Type Parameters (C# Programming Guide)

基本上此行出现问题:

current = newItem;

要使其按预期工作并保持此代码结构,然后执行以下操作:

class SomeType { }
class BinaryTree
{
    public SomeType root = null;

    public void Add(SomeType something)
    {
        Insert(ref root, something);
    }

    private void Insert(ref SomeType current, SomeType newItem)
    {
        if (current == null)
            current = newItem;
    }
}

以及用法

void Main()
{
    DataStructure ds = new DataStructure();
    ds.Add(new SomeType());
    Console.WriteLine(ds.root);
}