C# 如何检测循环引用?

标签 c#

对于 TreeList 的一个给定实例,如何检查要添加到第一个 TreeList 的另一个 TreeList 实例是否包含对第一个 TreeList 本身的(可能是间接的)引用(这将创建一个循环)引用)?

例如:

TreeList T1 = new TreeList();
TreeList T2 = new TreeList();
TreeList T3 = new TreeList();
T1.add(T2);
T2.add(T3);
T3.add(T1);

因为当我迭代这个过程时,我会陷入循环,因为在 T3 之后我会回到 T1。那么我如何检查订单中是否已包含一个。

class TreeList
{
    public string Name { get; set; }
    List<TreeList> items = new List<TreeList>();
    public ReadOnlyCollection<TreeList> Items
    {
        get { return items.AsReadOnly(); }
    }

    public TreeList(string Name)
    {
        this.Name = Name;
    }

    public void Add(string item)
    {
        items.Add(new TreeList(item));
    }
    public void Add(TreeList subTree)
    {
        items.Add(subTree);
    }
    public override string  ToString()
    {
        return Name;
    }
}

最佳答案

我认为这些方法会起作用:

public bool ContainsRecursively(TreeList node)
{
    foreach (TreeList child in items)
        if (child == node || child.ContainsRecursively(node))
            return true;

    return false;
}
public void Add(TreeList tree)
{
    if (this == tree) return; // this tree is 'tree', don't add ourselves!
    if (this.ContainsRecursively(tree)) return; // 'tree' is already in this tree
    if (tree.ContainsRecursively(this)) return; // this tree is already in 'tree'
    items.add(tree);
}

关于C# 如何检测循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275343/

相关文章:

c# - 验证唯一性

c# - 解析测量单位

c# - 将匿名类型列表转换为动态对象列表

c# - 图片框变大红色 X 但我无法检测或修复它

c# - 更优雅地处理属性更改事件监听器(很多)(字典?)

c# - 在 C# 中选择一系列线段

c# - 在 MVC 中使用 Ajax

c# - Windows 8 XAML : Tint an Image object

c# - 您如何访问委托(delegate)目标方法参数?

C#函数重载规则