예제 #1
0
        /// <summary>
        /// Metodo responsavel por encontrar o item de enum acordo com o grupo de valores e o valor
        /// </summary>
        /// <param name="enumerable">Tipo que deve ser um enum.</param>
        /// <param name="value">Valor correspondente ao item de enum</param>
        /// <returns>Resultado</returns>
        private static object Parse(Type enumerable, string value)
        {
            object[] attributes;
            Type     enumType;

            // se for um enum 'nulavel'
            if (IsNullable(enumerable))
            {
                // Validando se Type é um Enum
                enumType = new NullableConverter(enumerable).UnderlyingType;
                if (!enumType.IsEnum)
                {
                    throw new ArgumentException("The argument should be an enum", enumType.GetType().Name);
                }
            }
            else
            {
                // Validando se Type é um Enum
                if (!enumerable.IsEnum)
                {
                    throw new ArgumentException("The argument should be an enum", enumerable.GetType().Name);
                }
                else
                {
                    enumType = enumerable;
                }
            }

            foreach (FieldInfo info in enumType.GetFields())
            {
                if (!info.IsSpecialName)
                {
                    attributes = info.GetCustomAttributes(typeof(EnumValueAttribute), true);
                    if (attributes != null && attributes.Length > 0)
                    {
                        EnumValueAttribute enumValueAttribute;
                        for (int i = 0; i < attributes.Length; i++)
                        {
                            enumValueAttribute = (EnumValueAttribute)attributes[i];
                            if (enumValueAttribute.Value == value)
                            {
                                return(info.GetValue(null));
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidCastException("The attribute EnumValueAttribute not found on the type " + enumerable.Name);
                    }
                }
            }

            // se nao encontrar o valor do item, e o retorno aceitar nulo, retornar null
            if (string.IsNullOrWhiteSpace(value) && IsNullable(enumerable))
            {
                return(null);
            }

            //// nao foi encontrado um enum para o para group/value
            throw new InvalidCastException(string.Format("Unable to convert the value to an enum of type {0}", enumerable.Name));
        }