gpt4 book ai didi

c# - 实现父子类层次结构

转载 作者:太空宇宙 更新时间:2023-11-03 22:26:45 25 4
gpt4 key购买 nike

我发现很难找到一个像样的例子来说明如何实现父子层次结构类。我有一个 treeView 控件,我想将其转换为类层次结构,向每个节点添加额外数据,并能够使用 IEnumerable 轻松地遍历每个父节点。

public IEnumerable<Node> GetAllChildsFromParent(Node parent)
{
foreach (Node node in parent.NodeChildsCollection)
{
yield return node;
}
}

我已经实现了下面的代码,但卡住了,并没有真正实现知道我是否在正确的轨道上吗?我应该如何继续完成这项工作?

public class NodeChildsCollection : IEnumerable<Node>
{
IList<Node> nodeCollection = new List<Node>();
Node parent;

public Node Parent
{
get { return parent; }
set { parent = value; }
}

public NodeChildsCollection()
{
}


public void AddNode(Node parent, Node child)
{
this.parent = parent;
nodeCollection.Add(child);
}

#region IEnumerable<Node> Members

public IEnumerator<Node> GetEnumerator()
{
foreach (Node node in nodeCollection)
{
yield return node;
}
}

#endregion

#region IEnumerable Members

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

#endregion
}

public class Node
{

NodeChildsCollection nodeChildsCollection = new NodeChildsCollection();

public Node Parent
{
get { return nodeChildsCollection.Parent; }
set { nodeChildsCollection.Parent = value; }
}


public void AddChild(Node child)
{
nodeChildsCollection.AddNode(this, child);
}
}

最佳答案

您将节点的职责与集合的职责混合在一起。看看你是如何在集合中设置父级的?它不是具有父级的集合;它的节点。

我会像这样构造我的节点:

public class Node
{
public Node Parent {get;set;} // null for roots

public NodeCollection Children {get; private set;}

public Node()
{
Children = new NodeCollection();
Children.ChildAdded += ChildAdded;
Children.ChildRemoved += ChildRemoved;
};
private void ChildAdded(object sender, NodeEvent args)
{
if(args.Child.Parent != null)
throw new ParentNotDeadYetAdoptionException("Child already has parent");
args.Child.Parent = this;
}
private void ChildRemoved(object sender, NodeEvent args)
{
args.Child.Parent = null;
}
}

NodeCollection 看起来像

public class NodeCollection : INodeCollection {/*...*/}

INodeCollection 将是:

public interface INodeColleciton : IList<Node>
{
event EventHandler<NodeEvent> ChildAdded;
event EventHandler<NodeEvent> ChildRemoved;
}

集合职责在节点的子集合属性上。当然,您可以让节点实现 INodeCollection,但这是编程品味的问题。我更喜欢拥有 Children 公共(public)属性(property)(框架的设计方式)。

使用此实现,您无需实现“GetChildren”方法;公共(public) child 属性(property)为所有人提供。

关于c# - 实现父子类层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1120458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com