Ejemplo n.º 1
0
            /// <summary>
            /// Initializes enum conversion for the given type
            /// </summary>
            static EnumConverter()
            {
                //Setup
                Type enumType = typeof(T);

                T[] values = (T[])Enum.GetValues(enumType);
                Min = int.MaxValue;
                Max = int.MinValue;
                List <string> tempNames  = new List <string>(values.Length);
                List <T>      tempValues = new List <T>(values.Length);


                //Loop through the values
                for (int i = 0; i < values.Length; i++)
                {
                    //Get current value
                    T      value = (T)values.GetValue(i);
                    string name  = Enum.GetName(enumType, value);

                    //Check if the value is valid
                    if (!string.IsNullOrEmpty(name) && !ValueToName.ContainsKey(value) && !NameToValue.ContainsKey(name))
                    {
                        //Get numerical value
                        try
                        {
                            int numValue = value.ToInt32(null);
                            Min = Math.Min(Min, numValue);
                            Max = Math.Max(Max, numValue);
                        }
                        catch { /* Error suppression is intended, values outside of range have undefined behaviour*/ }

                        tempNames.Add(name);
                        tempValues.Add(value);
                        ValueToName.Add(value, name);
                        NameToValue.Add(name, value);
                    }
                }

                //Set final data
                if (Max == int.MinValue)
                {
                    Max = 0;
                }
                if (Min == int.MaxValue)
                {
                    Min = 0;
                }

                Names  = tempNames.AsReadOnly();
                Values = tempValues.AsReadOnly();
            }
Ejemplo n.º 2
0
 public Maybe <T, string> TryParse(string str)
 {
     return(NameToValue.TryGetValue(str, out T val) ? val : string.Concat(str, " cannot be parsed as an enum of type ", TypeName));
 }