public static IWrappedDictionary CreateDictionaryWrapper(object dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); Type dictionaryDefinition; if (ReflectionUtils.ImplementsGenericDefinition(dictionary.GetType(), typeof(IDictionary <,>), out dictionaryDefinition)) { Type dictionaryKeyType = ReflectionUtils.GetDictionaryKeyType(dictionaryDefinition); Type dictionaryValueType = ReflectionUtils.GetDictionaryValueType(dictionaryDefinition); // Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor Func <Type, IList <object>, object> instanceCreator = (t, a) => { ConstructorInfo c = t.GetConstructor(new[] { dictionaryDefinition }); return(c.Invoke(new[] { dictionary })); }; return((IWrappedDictionary)ReflectionUtils.CreateGeneric(typeof(DictionaryWrapper <,>), new[] { dictionaryKeyType, dictionaryValueType }, instanceCreator, dictionary)); } else if (dictionary is IDictionary) { return(new DictionaryWrapper <object, object>((IDictionary)dictionary)); } else { throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType())); } }
public static IWrappedList CreateListWrapper(object list) { ValidationUtils.ArgumentNotNull(list, "list"); Type listDefinition; if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(IList <>), out listDefinition)) { Type collectionItemType = ReflectionUtils.GetCollectionItemType(listDefinition); // Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor Func <Type, IList <object>, object> instanceCreator = (t, a) => { ConstructorInfo c = t.GetConstructor(new[] { listDefinition }); return(c.Invoke(new[] { list })); }; return((IWrappedList)ReflectionUtils.CreateGeneric(typeof(ListWrapper <>), new[] { collectionItemType }, instanceCreator, list)); } else if (list is IList) { return(new ListWrapper <object>((IList)list)); } else { throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType())); } }
public static bool IsDictionaryType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); if (typeof(IDictionary).IsAssignableFrom(type)) { return(true); } if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary <,>))) { return(true); } return(false); }
public static bool IsCollectionType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); if (type.IsArray) { return(true); } if (typeof(ICollection).IsAssignableFrom(type)) { return(true); } if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(ICollection <>))) { return(true); } return(false); }