To start, I have something like this:
class Parent
{
int x;
public Parent(int _x)
{
x = _x
}
}
class Child1: Parent
{
int y;
public Child1(int _y):base(_y)
{
y=_y;
}
}
class Child2: Parent
{
int z;
public Child2(int _z):base(_z)
{
z=_z;
}
}
A simple parent-child hierarchy. Then, I have a List which is actually full of Child1 and Child2. I want to make copies of each object in the list, and I want to start by making a new item that will be the copy.
But, if I do this:
foreach(Parent p in list)
dictionaryOfCopies.Add(p, new Parent(p.x));
then the dictionary will be full of Parent’s, not Children1 and Children2. Is there a way to invoke the constructor of an object that is typed as its parent type without knowing the specific type of the object?
One way to do it would be to implement the
ICloneableinterface on your objects, and let each instance clone itself.Then, you would use it like so:
To be the devil’s advocate, one of the criticisms I’ve seen of the
ICloneableinterface is that it’s not type-safe. If that’s irksome to you, you can still take the same idea, but implement your own version of theClonemethod that returnsParentinstead ofobject.