通过向列表添加元素来实现子/父关系

时间:2013-03-03 12:26:55

标签: c# .net events

我必须实现一个包含父字段和子字段的类。问题是,通过添加一个孩子,它必须立即保持对其父母的引用。我实现了它似乎工作,但我不确定我做对了。任何建议都会有用!

namespace DocumentToDocument
{
  public class MyEventArgs<T>: EventArgs
  {
    public T D;
  }

  public class MyList<T> : List<T>
  {
    public event EventHandler OnAdd;

    public new void Add(T item)
    {
      if (null != OnAdd)
      {
        var m = new MyEventArgs<Document> {D = item as Document};

        OnAdd(this, m);
      }
      base.Add(item);
    }
   }

   public class Document
   {
     public Document()
     {
       Children = new MyList<Document>();
       Children.OnAdd += new EventHandler(Children_OnAdd);
     }

     public string Name;

     public Document Parent;

     public MyList<Document> Children;

     public void Children_OnAdd(object sender, EventArgs e)
     {
      ((MyEventArgs<Document>) e).D.Parent = this;
     }
   }

   class Program
   {
     private static void Main(string[] args)
     {
       var d = new Document {Name = "I am a parent"};

       var dd = new Document {Name = "I am a child"};

       d.Children.Add(dd);
     }
   }
 }

0 个答案:

没有答案