我正在实现二叉树,并且在理解引用类型方面遇到了一些问题。
这不是实现本身,而是在我脑海中产生混乱的代码段。
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
新对象时,我希望它出现在root
字段下,因为我传递了一个引用,对吧?但相反,我在root
下得到了null
.
我的理解有什么问题?
引用类型的变量不直接包含其数据;它包含对其数据的引用。按值传递引用类型参数时,可以更改属于引用对象的数据,例如类成员的值。但是,不能更改引用本身的值;例如,不能使用相同的引用为新类分配内存并使其保留在方法外部。为此,请使用ref
或out
关键字传递参数。
文档:传递引用类型参数(C# 编程指南(
基本上问题出现在这一行上:
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);
}