【发布时间】:2015-08-18 02:08:52
【问题描述】:
我正在编写将从树结构返回特定节点的函数。但是当我使用 LINQ 在树中搜索时,它会在第一个分支中搜索,最后当它到达叶子时,它会抛出空引用异常,因为叶子没有任何子节点。
这是我的课,
public class Node
{
public int Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public IEnumerable<Node> Children { get; set; }
public IEnumerable<Node> GetNodeAndDescendants() // Note that this method is lazy
{
return new[] { this }
.Concat(Children.SelectMany(child => child.GetNodeAndDescendants()));
}
}
这就是我调用这个函数的方式,
var foundNode = Location.GetNodeAndDescendants().FirstOrDefault(node => node.Name.Contains("string to search"));
或
var foundNode = Location.GetNodeAndDescendants().FirstOrDefault(node => node.Id==123)
这样做的正确方法是什么?任何示例代码都将不胜感激
【问题讨论】:
-
为什么一开始就让代码遇到 NullReferenceException?叶子不应该返回一个包含零元素而不是 null 的 Children 集合,从而避免 NullReferenceException 吗?无需代码示例 - 只需查看 NullReferenceException 的堆栈跟踪以了解导致它的原因,然后从那里开始研究如何纠正代码的行为...
-
哦,按照@elgonzo 的建议工作。