删除父对象时删除子对象

时间:2015-11-27 15:21:31

标签: c# object reference

对你们大多数人来说,这可能是一个简单的问题!

名为 childList 的列表包含对 c2Child 类型的所有现有对象的引用。如果删除父对象,则还应删除对 childList 中的子元素的所有引用。

示例代码

class Program
{
    static List<c2> c2List;

    static void Main(string[] args)
    {
        c2List = new List<c2>();
        c2List.Add(new c2("obj1"));
        c2List.Add(new c2("obj2"));

        // new list with references to all child elements
        var childList = new List<c2Child>();
        foreach(var c2 in c2List)
            foreach(var child in c2.Childs)
                childList.Add(child);

        // delete "parent" objects
        c2List.Clear();

        // childList still has references to the childs even if the "parent" is deleted
        foreach(var child in childList)
            Console.WriteLine(child.name);

        Console.ReadLine();
    }
}

class c2
{
    public List<c2Child> Childs;
    public c2(string name)
    {
        Childs = new List<c2Child>();
        Childs.Add(new c2Child(name + "_1"));
        Childs.Add(new c2Child(name + "_2"));
    }
}

class c2Child
{
    public string name;
    public c2Child(string name)
    {
        this.name = name;
    }
}

输出:

  

obj1_1

     

obj1_2

     

obj2_1

     

obj2_2

所以基本上我要求删除父对象时删除所有子对象的可能性。我试图实现IDisposable但没有成功(称为c2List.Dispose()而不是c2List.Clear()和c2.Dispose()只是清除了子列表)。

0 个答案:

没有答案
相关问题