Пример #1
0
        public static Type[] GetElementTypes(Type enumerableType, IEnumerable enumerable,
                                             ElementTypeFlags flags = ElementTypeFlags.None)
        {
            if (enumerableType.HasElementType)
            {
                return(new[] { enumerableType.GetElementType() });
            }

            var idictionaryType = enumerableType.GetDictionaryType();

            if (idictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
            {
                return(idictionaryType.GetTypeInfo().GenericTypeArguments);
            }

            var ienumerableType = enumerableType.GetIEnumerableType();

            if (ienumerableType != null)
            {
                return(ienumerableType.GetTypeInfo().GenericTypeArguments);
            }

            if (typeof(IEnumerable).IsAssignableFrom(enumerableType))
            {
                var first = enumerable?.Cast <object>().FirstOrDefault();

                return(new[] { first?.GetType() ?? typeof(object) });
            }

            throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.",
                                        nameof(enumerableType));
        }
Пример #2
0
        public static Type[] GetElementTypes(Type enumerableType, IEnumerable enumerable,
            ElementTypeFlags flags = ElementTypeFlags.None)
        {
            if (enumerableType.HasElementType)
            {
                return new[] {enumerableType.GetElementType()};
            }

            Type idictionaryType = enumerableType.GetDictionaryType();
            if (idictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
            {
                return idictionaryType.GetTypeInfo().GenericTypeArguments;
            }

            Type ienumerableType = enumerableType.GetIEnumerableType();
            if (ienumerableType != null)
            {
                return ienumerableType.GetTypeInfo().GenericTypeArguments;
            }

            if (typeof(IEnumerable).IsAssignableFrom(enumerableType))
            {
                var first = enumerable?.Cast<object>().FirstOrDefault();

                return new[] {first?.GetType() ?? typeof(object)};
            }

            throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.",
                nameof(enumerableType));
        }