Enums or Tables?

后端 未结 9 913
天命终不由人
天命终不由人 2021-02-06 08:38

I am making this a community wiki, as I would appreciate people\'s approach and not necessarily an answer.

I am in the situation where I have a lot of lookup type data

9条回答
  •  不知归路
    2021-02-06 09:11

    One way is to write a formatter that can turn you enum into string representations:

    public class SalaryFormatter : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type formatType)
        {
             return (formatType == typeof(ICustomFormatter)) ? new
             SalaryFormatter () : null;
        }
    
        public string Format(string format, object o, IFormatProvider formatProvider)
        {
            if (o.GetType().Equals(typeof(Salary)))
            {
                return o.ToString();
    
                Salary salary = (Salary)o;
                switch (salary)
                {
                    case Salary.Low:
                         return "0 - 25K";
                    case Salary.Mid:
                         return "25K - 100K";
                    case Salary.High:
                         return "100K+";
                    default:
                         return salary.ToString();
                }
            }
    
        return o.ToString();
        }
    }
    

    You use the formatter like any other formatter:

    Console.WriteLine(String.Format(new SalaryFormatter(), "Salary: {0}", salary));
    

    The formatter can be extented to support different formats through formatting strings, multiple types, localization and so on.

提交回复
热议问题