Task: quickly fill in the fields of the decorator class

Suppose we have Modelseveral properties on it, and we want to create a decorator class for this model to improve it with some additional properties. Now we want to create a new instance DecoratedModelfilled with all the property values Model, possibly using the constructor with Modelas a parameter:

public class DecoratedModel : Model
{
    public DecoratedModel(Model baseModel)
    {
        // Populate decorated model generically from baseModel
    }
}

What would be the most common, concise way to populate DecoratedModelout Model?

+3
source share
2 answers

, , , . , - :

        public DecoratedModel(Model m)
        {
            foreach (var prop in typeof(Model).GetProperties())
            {
                this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(m, null),null);
            }
        }
+5

, Decorator, , , , .

public class DecoratedModel : Model
{
    public DecoratedModel(Model baseModel)
        : base(baseModel)
    {
        // Populate decorated model generically from baseModel
    }
}

public class Model
{
    public Model(Model copy)
    {
        this.x = copy.x;
        // etc.
    }
}
+2

All Articles