我使用从TreeNode派生的类,因此我可以为每个节点添加自定义属性
public class CustomNode : TreeNode
{
public int preloadIndex;
public string uniqueID = "0";
public int layer;
public string internalName;
public bool lsActive;
}
在某些时候,我的代码正在将一堆节点收集到List中,我需要从每个节点的父节点获取自定义属性。
List<CustomNode> NodeList = new List<CustomNode>;
//some nodes are collected into the list
foreach (var aNode in NodeList)
{
CustomNode parentNode = (CustomNode)aNode.Parent;
int parentIndex = parentNode.preloadIndex;
string parentID = parentNode.uniqueID;
}
问题是aNode.Parent返回一个TreeNode而不是我的自定义类,并像我上面尝试的那样投射它并不起作用。
未处理的类型&#39; System.InvalidCastException&#39;发生在myProject.exe中 附加信息:无法转换类型为#System; Windows.Forms.TreeNode&#39;的对象。输入&#39; myProject.CustomNode&#39;。
转换aNode.parent as CustomNode
并不起作用,它会返回null
。
TreeNodeCollection.Find
也会返回TreeNode
。
有没有办法获得父节点,最好不要遍历整个TreeView
?
答案 0 :(得分:0)
在CustomNode中编写Parent方法的覆盖。 (未经测试的代码)
public class CustomNode : TreeNode
{
public int preloadIndex;
public string uniqueID = "0";
public int layer;
public string internalName;
public bool lsActive;
public new CustomNode Parent()
{
return (CustomNode)base.Parent;
}
}
答案 1 :(得分:0)
我认为这里的问题是继承的概念。基本上,你不能让一个物体成为它从未有过的东西。仅仅因为CustomNode
来自TreeNode
并不意味着任何TreeNode
都是CustomNode
。
真正的解决方案在于您没有向我们展示的代码,即您TreeView
的创建。您需要在此处创建CustomNode
的实例并将其添加到TreeView
。您的CustomNode
可以根据您的需要覆盖或“遮蔽”事件和属性。
在您的情况下,您的NodeList
对象中可能会找到另一种解决方案。如果,且仅当时,您需要的每个CustomNode
都在该列表中,包括所有父母和子女,那么您只需将List
更改为Dictionary
即可密钥是CustomNode.Name
属性。所以你的代码将成为:
var nodeList = new Dictionary<string, CustomNode>();
//some nodes are collected into the list, like this:
var cn = new CustomNode();
nodeList.Add(cn.Name, cn);
foreach (var aNode in nodeList.Values)
{
var parentNode = nodeList[aNode.Parent.Name];
int parentIndex = parentNode.preloadIndex;
string parentID = parentNode.uniqueID;
}
答案 2 :(得分:0)
Radu,将您的代码更改为:
CustomNode parentNode = aNode.Parent as CustomNode;
if ( parentNode != null ){
int parentIndex = parentNode.preloadIndex;
string parentID = parentNode.uniqueID;
}
如果as运算符不是CustomNode
,则返回null此致