Enums or Tables?

后端 未结 9 1079
天命终不由人
天命终不由人 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:13

    For static items I use Enum with [Description()] attribute for each element. And T4 template to regenerate enum with descriptions on build (or whenever you want)

    public enum EnumSalary
        {
            [Description("0 - 25K")] Low,
            [Description("25K - 100K")] Mid,
            [Description("100K+")] High
        }
    

    And use it like

    string str = EnumSalary.Mid.Description()
    

    P.S. also created extension for System.Enum

    public static string Description(this Enum value) {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false );
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }
    

    and reverse to create enum by description

    public static TEnum ToDescriptionEnum(this string description)
    {
        Type enumType = typeof(TEnum);
        foreach (string name in Enum.GetNames(enumType))
        {
            var enValue = Enum.Parse(enumType, name);
            if (Description((Enum)enValue).Equals(description)) {
                return (TEnum) enValue;
            }
        }
        throw new TargetException("The string is not a description or value of the specified enum.");
    }
    

提交回复
热议问题