コード例 #1
0
        public static T GetEnumValue <T>(this int value)
        {
            if (Enum.IsDefined(typeof(T), value))
            {
                return((T)Enum.ToObject(typeof(T), value));
            }

            FeedbackManager.SendFeedback(() => $@"Failed to cast ""{value}"" to enum ""{typeof(T).Name}""");
            return((T)Enum.ToObject(typeof(T), -1));
        }
コード例 #2
0
        public static T GetEnumValue <T>(this string value)
            where T : struct
        {
            if (string.IsNullOrEmpty(value))
            {
                return((T)Enum.ToObject(typeof(T), -1));
            }

            var enumType = typeof(T);

            if (EnumStringCache.ContainsKey(enumType))
            {
                if (EnumStringCache[enumType].ContainsKey(value))
                {
                    return((T)EnumStringCache[enumType][value]);
                }
            }
            else
            {
                EnumStringCache.Add(enumType, new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase));
            }

            if (Enum.TryParse(value, true, out T enumValue))
            {
                EnumStringCache[enumType][value] = enumValue;
                return((T)EnumStringCache[enumType][value]);
            }

            var enumValues = Enum.GetValues(typeof(T)).Cast <object>();
            var enumObject = enumValues.FirstOrDefault(
                v =>
            {
                var jsonProperty = ((Enum)v).JsonProperty();
                return(jsonProperty != null && jsonProperty.Equals(value, StringComparison.OrdinalIgnoreCase));
            });

            if (enumObject != null)
            {
                EnumStringCache[enumType][value] = (T)enumObject;
                return((T)EnumStringCache[enumType][value]);
            }

            FeedbackManager.SendFeedback(() => $@"Failed to parse enum ""{typeof(T).Name}"" from ""{value}""");
            return((T)Enum.ToObject(typeof(T), -1));
        }