mercredi 18 juillet 2018

Copy instances of derived class based on properties with attributes

Suppose I have an abstract base class in which I want a CreateCopy method:

public abstract class BaseClass
{
    ///base stuff

    public BaseClass CreateCopy() //or public object, if necessary   
    {
        //?????
    }
}

Assume that all derived classes have a parameterless constructor and property fields (that can be) marked with some kind of attribute:

public class DerivedClass : BaseClass
{
    [CopiableProperty]
    public string Property1 {get; private set;}

    [CopiableProperty]
    public int Property2 {get; private set;}

    //no need to copy
    public int Property3 {get; private set;}

    //parameterless constructor
    public DerivedClass() { }
}

Is it possible with this structure to write the body of CreateCopy() in a way that I can create new instances of the derived objects with the correct CopiableProperty fields?


Naturally I could make a public abstract BaseClass CreateCopy() and force each derived class to care for its own copy, but due to the size and amount of the derived classes, this would bring too much extra effort.





Aucun commentaire:

Enregistrer un commentaire