Exemplo n.º 1
0
        /// <summary>
        /// A formatter implementation that resolves a <see cref="IDictionary"/>.
        /// </summary>
        /// <param name="hierarchy">The hierarchy to parse.</param>
        /// <param name="valueTypes">The value types that forms a <see cref="KeyValuePair{TKey,TValue}"/>.</param>
        /// <returns>A <see cref="IDictionary"/> with <see cref="KeyValuePair{TKey,TValue}"/> of <paramref name="valueTypes"/> from the specified <paramref name="hierarchy"/>.</returns>
        public static IDictionary UseDictionary(this IHierarchy <DataPair> hierarchy, Type[] valueTypes)
        {
            var items       = hierarchy.Find(h => h.Instance.Name == EnumerableElementName && h.Depth == 1).SelectMany(h => h.GetChildren()).ToList();
            var dic         = typeof(Dictionary <,>).MakeGenericType(valueTypes);
            var dicInstance = Activator.CreateInstance(dic);
            var addMethod   = dic.GetMethod("Add");

            foreach (var item in items.ParseDictionaryItem(valueTypes))
            {
                addMethod.Invoke(dicInstance, new[] { item.Key, item.Value });
            }
            return(dicInstance as IDictionary);
        }
Exemplo n.º 2
0
        /// <summary>
        /// A formatter implementation that resolves a <see cref="ICollection"/>.
        /// </summary>
        /// <param name="hierarchy">The hierarchy to parse.</param>
        /// <param name="valueType">The type of the objects in the collection.</param>
        /// <returns>A <see cref="ICollection"/> of <paramref name="valueType"/> from the specified <paramref name="hierarchy"/>.</returns>
        public static ICollection UseCollection(this IHierarchy <DataPair> hierarchy, Type valueType)
        {
            var items        = hierarchy.Find(h => h.Instance.Name == EnumerableElementName && h.Depth == 1).SelectMany(h => h.GetChildren()).ToList();
            var list         = typeof(List <>).MakeGenericType(valueType);
            var listInstance = Activator.CreateInstance(list);
            var addMethod    = list.GetMethod("Add");

            foreach (var item in items.ParseCollectionItem(valueType))
            {
                addMethod.Invoke(listInstance, new[] { item });
            }
            return(listInstance as ICollection);
        }