I have to implement a class with has parent and child fields. The problem is that by adding a child it must immediately keep reference to its' parent. I implemented it and it seems to work but I am not quite sure if I did it right. Any advice will be useful!
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);
}
}
}
MyList<>
- when used asList<>
orIList<>
the original implementation ofAdd()
would come to bear. This violates the Liskov Substitution Principle and would cause problems when using any LINQ extension methods that may useAdd()
. \$\endgroup\$new
is hardly ever a good solution, and particularly so in this case, as what you actually want is an override, butnew
can't give you that. \$\endgroup\$