请理解,我看到和跟踪的问题,但不知道如何解决它干净。我正在尝试运行我的Add方法,迭代直到找到我的键或当前节点为null,然后返回对该节点的引用,如果它为null,则分配。我的代码(请参阅add方法中的注释):
public class MyClass<TKey, TValue>
{
private Node _baseNode;
public void Add(TKey key, TValue value)
{
var newNode = new Node(key, value);
//this returns null, as is expected.
var nodeToUpdate = TraverseDown(ref _baseNode, newNode.Key);
if (nodeToUpdate != null)
throw new ArgumentException("Cannot add a duplicate key.");
//here, I try to assign a value to _baseNode because I'd like
//nodeToUpdate to hold the reference to _baseNode
nodeToUpdate = newNode;
}
private Node TraverseDown(ref Node currentNode, int keyToFind)
{
if (currentNode == null || currentNode?.Key == keyToFind
|| currentNode?.Edge == null)
{
//on first add, this is what is getting hit - as expected
return currentNode;
}
else
{
//these are being explicitly set to local variables because i was
//experimenting with passing them byRef, and that can't be done on
//properties
var leftNode = currentNode.Edge.LeftNode;
var rightNode = currentNode.Edge.RightNode;
return keyToFind < currentNode.Key
? TraverseDown(ref leftNode, keyToFind)
: TraverseDown(ref rightNode, keyToFind);
}
}
}让TraverseDown方法接受Node byRef的全部意义是尝试返回对已经找到的任何节点的引用,即使它是null。在本例中,这是添加的第一项,因此TraverseDown方法应该返回对我的_baseNode的引用,null是默认的。但是,只需将局部变量设置为newNode,而_baseNode仍然为null。
我相信有一个简单的答案,但我已经研究了一点点,但什么也没有发现。拜托,任何帮助都是非常感谢的!
发布于 2016-12-29 06:53:01
在TraverseDown方法中没有实际分配ref currentNode的行。相反,您返回它的值。当您传递一个ref参数时,并不意味着该值将被视为整个方法范围内的引用。参数本身将被视为引用,而不是其值。所以当你写..。
return currentNode;返回currentNode的值,而不是引用。因为值是null,所以您总是返回null (因为您的if (currentNode == null...语句)。
当你指派..。
nodeToUpdate = newNode;...you只需分配一个null引用。
当您实际希望在_baseNode中为TraverseDown赋值时,需要在方法中设置currentNode:
currentNode = //Value注意在C# 7.0中,将有参考资料返回,它的行为方式是在您的方法中对待currentNode。
https://stackoverflow.com/questions/41374338
复制相似问题