如何在C#中返回类成员字段引用以简化二叉树代码
如何通过返回字段引用简化二叉树Add方法的重复代码?
我希望简化二叉树Add方法中的重复代码,将针对左、右子节点的相同操作合并。当前代码在条件分支中分别处理LeftChild和RightChild,存在大量重复逻辑,我想通过一个方法直接返回对应子节点的字段引用,从而统一后续的操作逻辑。
现有代码结构
类定义
public class BinaryTree<TNode, TCost> { // 其他成员 public void Add(TNode newNode, TCost newKey) { // 待简化的重复逻辑位于此处 } } public class TreeNode<TNode, TCost> { public TreeNode? LeftChild; // 对应原逻辑中的VarA public TreeNode? RightChild; // 对应原逻辑中的VarB public TCost NodeKey; public TNode NodeInfo; public TreeNode? Parent; // 构造新节点时需要设置的父节点引用 }
Add方法中的重复逻辑
// BinaryTree类的Add方法内部 TreeNode<TNode, TCost> currentNode = RootNode; bool foundPosition = false; while (!foundPosition) { if (newKey > currentNode.NodeKey) // 转向右子树 { if (currentNode.RightChild == null) { TreeNode<TNode, TCost> newLeaf = new TreeNode<TNode, TCost>(newNode, newKey) { Parent = currentNode }; currentNode.RightChild = newLeaf; foundPosition = true; } else { currentNode = currentNode.RightChild; } } else // 转向左子树 { if (currentNode.LeftChild == null) { TreeNode<TNode, TCost> newLeaf = new TreeNode<TNode, TCost>(newNode, newKey) { Parent = currentNode }; currentNode.LeftChild = newLeaf; foundPosition = true; } else { currentNode = currentNode.LeftChild; } } } // 后续还有其他无关代码,因此不能在foundPosition=true时直接终止方法
期望的简化写法
我希望将上述重复逻辑合并,通过一个方法获取对应子节点的引用,统一执行后续操作:
TreeNode<TNode, TCost> currentNode = RootNode; bool foundPosition = false; while (!foundPosition) { // 需要实现AppropriateChild方法,返回LeftChild或RightChild的字段引用 ref TreeNode<TNode, TCost>? nextChild = ref currentNode.AppropriateChild(newKey); if (nextChild == null) { TreeNode<TNode, TCost> newLeaf = new TreeNode<TNode, TCost>(newNode, newKey) { Parent = currentNode }; nextChild = newLeaf; // 若不用引用,此处仅修改局部变量,无法更新原节点的子字段 foundPosition = true; } else { currentNode = nextChild; } } // 后续其他无关代码
尝试过的方法及问题
我尝试编写返回字段引用的方法,但编译失败:
// TreeNode类内部 public ref TreeNode<TNode, TCost>? AppropriateChild(TCost targetCost) { if (targetCost > this.NodeKey) { return ref RightChild; // 编译错误 } else { return ref LeftChild; // 编译错误 } }
如果仅返回节点实例,赋值操作只会修改局部变量,无法更新原节点的LeftChild/RightChild字段:
public TreeNode<TNode, TCost>? AppropriateChild(TCost targetCost) { if (targetCost > this.NodeKey) { return RightChild; } else { return LeftChild; } }
请问我的目标是否可实现?若可以,该如何编写代码?
内容的提问来源于stack exchange,提问作者citronnade
相关产品推荐
相关产品推荐

