Ejemplo n.º 1
0
 private static bool IsCollectionType(Type type, ITypeCache typeCache, object itemValue)
 {
     return
         ((type.IsArray || typeCache.IsGeneric(type) &&
           typeCache.IsTypeAssignableFrom(typeof(System.Collections.IEnumerable), type)) &&
          (itemValue as System.Collections.IEnumerable) != null);
 }
Ejemplo n.º 2
0
        private static object ConvertCollection(Type type, ITypeCache typeCache, object itemValue)
        {
            var elementType = type.IsArray
                ? type.GetElementType()
                : typeCache.IsGeneric(type) && typeCache.GetGenericTypeArguments(type).Length == 1
                    ? typeCache.GetGenericTypeArguments(type)[0]
                    : null;

            if (elementType == null)
            {
                return(null);
            }

            var count      = GetCollectionCount(itemValue);
            var arrayValue = Array.CreateInstance(elementType, count);

            count = 0;
            foreach (var item in (itemValue as System.Collections.IEnumerable))
            {
                arrayValue.SetValue(ConvertSingle(elementType, typeCache, item), count++);
            }

            if (type.IsArray || typeCache.IsTypeAssignableFrom(type, arrayValue.GetType()))
            {
                return(arrayValue);
            }
            else
            {
                var collectionTypes = new []
                {
                    typeof(IList <>).MakeGenericType(elementType),
                    typeof(IEnumerable <>).MakeGenericType(elementType)
                };
                var collectionType = type.GetConstructor(new [] { collectionTypes[0] }) != null
                    ? collectionTypes[0]
                    : collectionTypes[1];
                var activator = _collectionActivators.GetOrAdd(new Tuple <Type, Type>(type, collectionType), t => type.CreateActivator(collectionType));
                return(activator?.Invoke(arrayValue));
            }
        }