这是代码:
private TreeNode GetTopLevelNode(TreeNode childNode)
{
if (childNode == null)
throw new ArgumentNullException("childNode", "childNode is null.");
if (childNode.Parent == null) return childNode;
TreeNode node = childNode;
while (true)
{
if (node.Parent == null)
{
return node;
}
node = node.Parent;
}
}
在while循环中,只有当node.Parent == null时,才会返回一个节点,
为什么编译器不报“并非所有代码路径都返回值”的错误?
如果不能满足'node.Parent == null',则不会返回任何树节点。 编译器无法检测到这种情况?
最佳答案
因为您正在使用 while(true){
,所以除了使用 return 之外没有其他方法可以退出循环。如果 node.parent == null
不能满足,那么就会死循环。因此,没有返回就无法通过循环,编译器也不会报错。
此外,您指定的代码几乎总是会返回空 TreeNode
,这是您真正想要的吗?
编辑:我看到你解决了这个问题。
关于c# - 为什么在这种情况下编译器不提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2047177/