net列表.查找运行时错误
本文关键字:运行时错误 查找 列表 net | 更新日期: 2023-09-27 18:07:13
我正在构建一个自定义数据结构来容纳TreeView,以便我可以序列化它。这一点是无关的,是背景,但我把它放在这里。
我有一个CustomNode类和树视图将在List<CustomNode>
中举行:
private class CustomNode
{
public CustomNode()
{}
public CustomNode (string name)
{
NodeName = name;
}
public string NodeName { get; set; }
public int Level { get; set; }
public int Index { get; set; }
public CustomNode parent;
public List<CustomNode> children;
}
这就是我想解决的相关问题。在我的代码中,我想找到一个特定CustomNode的父节点,所以我这样做:
CustomNode customNode = new CustomNode();
//initialise properties of customNode (below)
.
.
.
CustomNode customNodeParent = new CustomNode();
customNodeParent = listOfCustomNodes.Find(_customNode => (_customNode.Index == node.Index && _customNode.Level == node.Level));
customNode.Index = customNodeParent.children.Count;
最后一行抛出未设置为对象实例的Object引用。例外。我不明白为什么会这样。
EDIT:还有一个问题。在我调用
的地方customNode.Index = customNodeParent.children.Count;
customNodeParent为空。我知道发生了什么。不是找到节点。
在您的CustomNode
声明中,更改
public List<CustomNode> children;
public List<CustomNode> children = new List<CustomNode>();
在您当前的代码中,您说"CustomNode
有一个名为children
的字段,其类型为List<CustomNode>
",但该字段的值从未设置,因此当创建CustomNode
时,children
是null
。
通过上述更改,你说"当第一次创建时,CustomNode
的children
是一个实际对象,一个新的List<CustomNode>
"。因为这是一个实际的对象,而不是null
,所以请求它的Count
是安全的。
因为customNodeParent.children
是空的
你需要在使用customNodeParent.children
之前实例化它。
最容易在声明中完成,然后可能在构造函数中完成,最后在类之外的实例化代码中完成。