Enums的自定义属性是否危险?

EAM*_*ann 27 c# enums attributes

我正在构建一个大量使用Enums来自定义数据的应用程序.实质上,对象存储在数据库中,具有大约28个单独的属性.每个属性都是一个双字符字段,从SQL直接转换为Enum.

不幸的是,我还需要将这些值转换为两个不同的人类可读值.一个用于数据表上的图例,另一个用于CSS类,用于在Web应用程序前端设置图像样式.

为此,我设置了两个自定义属性并将其应用到Enum必要的位置.例如:

自定义属性界面

public interface IAttribute<T>
{
    T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)

自定义属性示例

public sealed class AbbreviationAttribute: Attribute, IAttribute<string>
{
    private readonly string value;

    public AbbreviationAttribute(string value)
    {
        this.value = value;
    }

    public string Value
    {
        get { return this.value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

从中检索自定义属性的方法 Enum

public static R GetAttributeValue<T, R>(IConvertible @enum)
{
    R attributeValue = default(R);

    if (@enum != null)
    {
        FieldInfo fi = @enum.GetType().GetField(@enum.ToString());

        if (fi != null)
        {
            T[] attributes = fi.GetCustomAttributes(typeof(T), false) as T[];

            if (attributes != null && attributes.Length > 0)
            {
                IAttribute<R> attribute = attributes[0] as IAttribute<R>;

                if (attribute != null)
                {
                    attributeValue = attribute.Value;
                }
            }
        }
    }

    return attributeValue;
}
Run Code Online (Sandbox Code Playgroud)

Enum使用此模式的示例

public enum Download
{
    [Abbreviation("check")]
    [Description("Certified")]
    C = 1,

    [Abbreviation("no-formal")]
    [Description("No formal certification")]
    NF = 2,

    [Abbreviation("cert-prob")]
    [Description("Certified with potential problems")]
    CP = 3
}
Run Code Online (Sandbox Code Playgroud)

这两个AbbreviationDescription是实现自定义属性IAttribute<T>.我的实际Enum有11个可能的值,正如我之前提到的,它在我的自定义对象中的28个单独属性中使用.使用自定义属性似乎是来回映射此信息的最佳方式.

现在问题是,这是实现这一目标的最佳方法吗? 我将Enum值("C","NF"或"CP"存储在上面的代码段中)存储在数据库中,但我需要在代码中使用缩写和描述的值.此外,我怀疑这将是我需要的最后一组自定义属性.

在我继续推进这种模式之前...... 这是正确的做事方式吗? 我现在宁愿用这种方法解决潜在的问题,而不是后来跟踪和重构.

Sam*_*Axe 16

这与我使用的方法相同.一个缺点是序列化.自定义属性值不会序列化.

我喜欢数据库方法的自定义属性方法,因为它将属性数据绑定到枚举,而不必使用查找表或类等.