Consider I have 2 classes:
public class ComplicatedParent
{
// Lots of data
}
public class SimpleChild : ComplicatedParent
{
public string SomeAdditionalData { get; set; }
开发者_如何学运维
public SimpleChild(string arg) : base()
{
SomeAdditionalData = arg;
}
}
And SomeFunction
that returns instance of ComplicatedParent
. Is there a simple way to construct child from parent's reference, preserving parent's state?
Actually ComplicatedParent
class and SomeFunction
are third party so I can't change them.
You can't do this automatically in the language. You can do it with Automaper or by manual assignments.
The best way to do this would be to write a constructor for SimpleChild that takes an instance of ComplicatedParent as an argument. The constructor would then copy the data across. You could try using clone() to create a copy of the ComplicatedParent, cast it to a SimpleChild, add the additional data and return it.
For help on cloning you might want to have a gander at this link:
Deep cloning objects
If by "preserving parent state" you mean preserving let's say internal values of the parent class, you can not do that, you should implement it by yourself. Something like:
public static SimpleChildFromParent(ComplicatedParent cp); // static method in SimpleChild class.
//and somewhere in the code
SimpleChild sc = SimpleChild.SimpleChildFromParent(cp); // where cp is ComplicatedParent previously created and intialized.
Regards.
If you can override the properties of your parent, You can take the parent object in the child constructor and delegate the calls to the internal referenced parent. This is only possible if the parent properties are virtual.
If ComplicatedParent
really is that complex you should consider splitting it into smaller classes and store instances to these in ComplicatedParent
(aggregation, not inheritance). If these objects are immutable, implementing the construct-from-prototype should be easy.
As of the construction of the objects, consider the Prototype pattern.
精彩评论