【发布时间】:2019-05-08 05:05:59
【问题描述】:
我正在用 C# 编写一个图形库。
这是我的 Graph.cs:
public class Graph : IGraph
{
public HashSet<INode> Nodes { get; set; }
public HashSet<IEdge> Edges { get; set; }
}
- 规则 1:当一个 节点被删除,我想 被删除节点属于其中的所有边,都将从中删除 IEdge 的 HashSet。
- 规则 2:当添加 Edge 时,我想要 Edge 中的两个 Node 实例 实例添加到 INode 的 HashSet。
我该怎么做才能获得这种行为?
现在,图书馆用户只需使用:
g.Edges.Add(new Edge(n5, n6));
n5 和 n6 是 Node 实例,但 g.Nodes HashSet 中没有 n5 和 n6。
我想知道是否有一种方法可以在将 Edge 实例添加到 HashSet 在 Setter of Edges 属性中时调用这样的方法:
void UpdateNodes(IEdge edge)
{
Nodes.Add(edge.A_Node);
Nodes.Add(edge.Another_Node);
}
【问题讨论】:
-
您可以通过实现
INotifyCollectionChanged接口来包装/扩展HashSet<T>。然后,订阅CollectionChanged事件并根据需要处理更改。 -
HashSet<>看起来不容易扩展,但您始终可以添加一个实现上述INotifyCollectionChanged的包装器。 -
你可能想从QuickGraph获得一些灵感
标签: c# data-structures graph collections hashset