枚举或表格?

Dus*_*ine 7 c# enums

我正在制作一个社区维基,因为我会欣赏人们的方法而不一定是答案.

我处于这样的情况,我有很多查找类型数据字段,不会改变.一个例子是:

年薪工资
选择:0 - 25K
期权:25K - 100K
期权:100K +

我希望通过枚举轻松获得这些选项,但也希望在DB中提供文本值,因为我将报告文本值而不是ID.此外,由于它们是静态的,我不想调用DB.

我想在枚举和表格中重复这个,但是想听一些其他的想法.

谢谢

No *_*rns 7

我认为枚举是一个坏主意.只要给出您显示的数据类型,它就会发生变化.最好有一个数据库表,其中包含您在应用初始化时加载的ID/Min/Max/Description字段.

  • 如果它确实不会更改并且您没有数据库,则可以将其存储在自定义部分的app.config文件中. (2认同)

Che*_*rek 7

对于静态项,我使用Enum和每个元素的[Description()]属性.和T4模板重新生成枚举,包含构建描述(或任何你想要的)

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

并使用它

string str = EnumSalary.Mid.Description()
Run Code Online (Sandbox Code Playgroud)

PS还为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();
}
Run Code Online (Sandbox Code Playgroud)

并通过描述反向创建枚举

public static TEnum ToDescriptionEnum<TEnum>(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.");
}
Run Code Online (Sandbox Code Playgroud)