【问题标题】:Call a method when an object is added to HashSet property将对象添加到 HashSet 属性时调用方法
【发布时间】: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&lt;T&gt;。然后,订阅CollectionChanged 事件并根据需要处理更改。
  • HashSet&lt;&gt; 看起来不容易扩展,但您始终可以添加一个实现上述INotifyCollectionChanged 的包装器。
  • 你可能想从QuickGraph获得一些灵感

标签: c# data-structures graph collections hashset


【解决方案1】:

我不会直接公开 HashSet 集合。

public class Graph : IGraph
{
    private HashSet<INode> _nodes = new HashSet<INode>(); 
    private HashSet<IEdge> _edges = new HashSet<IEdge>();

    public IEnumerable<INode> Nodes => _nodes;
    public IEnumerable<IEdge> Edges => _edges;

    public void AddNode(INode node) => _nodes.Add(node); //Here you can extend with your own custom code.
    public void AddEdge(IEdge edge) => _edges.Add(edge);

    //Here you add other functions such as perhaps "Remove".
}

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2015-11-15
    • 2021-03-22
    相关资源
    最近更新 更多