Flomo Togba Kwele wrote:
I am having trouble with the following design. I want an object containing a Parent object and a
List of its Child objects. The Child object is abstract, so the List must contain concrete objects
derived from it.
When I instantiate the ParentChild object and add Child-derived objects to the List, I will be able
to add any object derived from Child. However, I want the List to contain only a single type
derived from Child, and I want methods using children to behave polymorphically.
I don't think this snippet will work. Can anyone suggest an alternative?
Thanks, Flomo
namespace Test {
class ParentChild {
private Parent parent;
private Child<Tchildren;
}
class Parent {}
abstract class Child {}
class ChildTypeA: Child {}
class ChildTypeB: Child{}
}
I'm not positive I follow your question, but if you want the list to
contain only a single type derived from Child then wouldn't you just
change this:
private Child<Tchildren; // This is invalid, BTW.
to this:
private List<ChildAchildren;
or to this:
private List<ChildBchildren;
depending upon which type you want to be in the list?
If you really do want a list of type List<Childbut limit which Child
types can be added to it then you could do something like this:
public class Mother
{
List<Childchildren = new List<Child>();
public Mother()
{
ChildA goodChild = new ChildA();
ChildB badChild = new ChildB();
children.Add(goodChild);
children.Add(badChild);
}
}
public class GoodList : List<Child>
{
new public void Add(Child item)
{
if (item is ChildB) return;
base.Add(item);
}
}
public abstract class Child { }
public class ChildA : Child { }
public class ChildB : Child { }
Or, better yet, since there really not point in limiting the members of
the list if you want those members to be polymorphic, implying the types
will be different (even though they'll have the same base type), just
filter them when you make the list:
if (goodChild is ChildA) children.Add(goodChild);
if (badChild is ChildA) children.Add(goodChild);
and you won't have to override the List.Add method.
A list can contain any type derived from the list's declared type and if
you only want specific subclasses of that declared type to be in the
list then one of the above two methods should work.
The Parent type is easy enough to deal with and seems to just add noise
to your question.
--
-glenn-