Thursday, March 24, 2011

Challenge: quickly populate the fields of a decorator class

Let's assume that we have a Model with several properties on it and we want to create a decorator class of this model to enhance it with some extra properties. Now we want to create a new instance of the DecoratedModel populated with all the property values of Model, perhaps using a constructor with Model as a parameter:

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

What would be the most generic, concise way to populate the DecoratedModel from the Model?

From stackoverflow
  • While it does require the Model class to have a copy constructor to copy the Model data in the Decorator class, doing this would at least ensure that for all Decorators, you only have to call the base class copy constructor.

    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.
        }
    }
    
  • Well, you should be able to use reflection to reflect over the base classes properties, and then use that to set the child classes properties. I haven't tested this extensively, but something like this might work:

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

0 comments:

Post a Comment