//----------------------------------------------------------------------- // // Copyright (c) 2009 Deltares. All rights reserved. // // Barry Faassen // barry.faassen@deltares.nl // 25-5-2009 // The object materializer can set property values // for a given type. Values can be set through action callback lambda // expressions as an alternative of using reflection. // //----------------------------------------------------------------------- namespace Deltares.Dam.Data { using System; using System.Collections.Generic; using System.Linq; public class ObjectMaterializer { private struct SetterInfo { public Action Function; public bool Required; } /// /// Holds the property setter actions with the name as the key of the setter /// private readonly Dictionary dict; /// /// Holds the list of actions in a list so it is accessible with an index /// private List setters; public ObjectMaterializer() { this.dict = new Dictionary(); this.setters = new List(); } /// /// Adds a new property setter /// /// The name of the setter /// The setter lambda expression /// public void Add(string setterName, Action func, bool required) { SetterInfo columnInfo = new SetterInfo() { Function = func, Required = required }; dict.Add(setterName, columnInfo); } public void Add(string setterName, Action func) { Add(setterName, func, true); } /// /// Removes a property setter /// /// The name of the setter public void Remove(string setterName) { dict.Remove(setterName); setters = dict.Values.ToList(); } /// /// Returns the mapped keys /// public IEnumerable MappingKeys { get { return this.dict.Keys; } } public bool IsRequired(string setterName) { return this.dict.ContainsKey(setterName) && this.dict[setterName].Required; } /// /// Gets the setter action by index /// /// The index of the property set expression /// public Action this[int index] { get { if (setters == null) setters = dict.Values.ToList(); return setters[index].Function; } } /// /// Gets the setter action by name /// /// The name of the property set expression /// public Action this[string name] { get { return dict[name].Function; } } /// /// Gets the number of setter items /// public int Count { get { return dict.Count; } } } }